从 DataTemplate 中的 DataTemplate 中引用 ViewModel 的 DataContext [英] Reference ViewModel's DataContext from within a DataTemplate in a DataTemplate
问题描述
我发现自己有点束手无策...绑定...呵呵...(跛脚)
I found myself in a bit of a bind... with bindings... hehe... (lame)
无论如何...我需要参考主 ViewModel 的属性,但是在 DataTemplate
中,它本身在另一个 DataTemplate
中...它看起来像Silverlight 允许的唯一 RelativeSource
模式是:Self 和 TemplatedParent.并且 TemplatedParent 上升得不够.
Anyway... I need to refer to the main ViewModel's Property, but from within a DataTemplate
, which is itself within another DataTemplate
... and it looks like the only RelativeSource
mode that Silverlight allows are: Self and TemplatedParent. And TemplatedParent doesn't go up enough.
有什么可以做的吗?
一些代码:
<phone:PanoramaItem>
<phone:LongListSelector Margin="0,-38,-22,2" ItemsSource="{Binding Items}">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<common:ItemContentTemplateSelector DataContext="{Binding}" Content="{Binding ItemContent}" HorizontalContentAlignment="Stretch" Margin="12,2,0,4">
<common:ItemContentTemplateSelector.DefaultTemplate>
<DataTemplate>
.....
</DataTemplate>
</common:ItemContentTemplateSelector.DefaultTemplate>
<common:ItemContentTemplateSelector.PhoneNumberTemplate>
<DataTemplate>
<Grid Background="White" Height="102">
<Border x:Name="border">
<TextBlock Text="Call"/>
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseLeftButtonDown">
<!-- BINDING ERROR -->
<i:InvokeCommandAction Command="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=DataContext.PhoneCallCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Border>
</Grid>
</DataTemplate>
</common:ItemContentTemplateSelector.PhoneNumberTemplate>
</common:ItemContentTemplateSelector>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
</phone:PanoramaItem>
推荐答案
如果您没有解决方法或无法轻松解决,有事要做;
If you don't wont a workaround or make it easily, There is something to do;
使用静态资源
看看这个;
MyViewModelClass ViewModel
{
get;set;
}
...ctor()
{
this.ViewModel=new MyViewModelClass();
this.DataContext=this.ViewModel; //We use same VM instance as DataContext as Resource
this.Resoureces.Add("MainVieModel",ViewModel);
InitializeComponents();//...Add resource before this line
}
之后你可以在任何你想要的地方同时使用你的ViewModel作为StaticResource;
After that you can use your ViewModel at the same time as a StaticResource anywhere you want;
{Binding Path=Items,Source={StaticResource ViewModel}}
我在 stackoverflow 的编辑器上编码.可能缺少一些字符...
I coded on stackoverflow's editor. There could be some missing chars ...
这篇关于从 DataTemplate 中的 DataTemplate 中引用 ViewModel 的 DataContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!