[英]Bind to DataContext of ItemsControl from within DataTemplate
I'm using an ItemsControl, boiled down, in this way: 我正在使用通过以下方式简化的ItemsControl:
<UserControl.Resources>
<DataTemplate x:Key="HomeItemTemplate">
<UserControl Command="{Binding DataContext.MyCommand}"/>
</DataTemplate>
</UserControl.Resources>
<ItemsControl ItemTemplate="{StaticResource HomeItemTemplate}" />
Now, the view this ItemsControl is placed in has a DataContext. 现在,此ItemsControl所在的视图具有DataContext。 In that DataContext I have my MyCommand.
在那个DataContext中,我有MyCommand。 I have to use this ItemsControl in multiple places, so directly referencing to an ElementName within the DataTemplate is something I don't want to do.
我必须在多个地方使用这个ItemsControl,所以我不想直接在DataTemplate中引用ElementName。
I tried TemplatedParent and RelativeSource, different stuff, I don't know what exactly I should do. 我尝试了TemplatedParent和RelativeSource,它们是不同的东西,我不知道该怎么做。 How would I have to write this so my UserControl can bind to the DataContext of the ItemsControl?
我该怎么写,这样我的UserControl才能绑定到ItemsControl的DataContext?
If you have a DataTemplate / ItemTemplate in a resource dictionary, you might want to use the {RelativeSource FindAncestor}
binding mode to bind to properties of the parent ItemsControl : 如果资源字典中有一个DataTemplate / ItemTemplate ,则可能需要使用
{RelativeSource FindAncestor}
绑定模式来绑定到父ItemsControl的属性:
<UserControl.Resources>
<DataTemplate x:Key="HomeItemTemplate">
<UserControl Command="{Binding DataContext.MyCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}}}"/>
</DataTemplate>
</UserControl.Resources>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.