C# 从DataTemplate内绑定到ItemsControl的DataContext

C# 从DataTemplate内绑定到ItemsControl的DataContext,c#,xaml,binding,datatemplate,C#,Xaml,Binding,Datatemplate,我使用的是ItemsControl,简而言之,是这样的: <UserControl.Resources> <DataTemplate x:Key="HomeItemTemplate"> <UserControl Command="{Binding DataContext.MyCommand}"/> </DataTemplate> </UserControl.Resources> <ItemsControl Ite

我使用的是ItemsControl,简而言之,是这样的:

<UserControl.Resources>
  <DataTemplate x:Key="HomeItemTemplate">
    <UserControl Command="{Binding DataContext.MyCommand}"/>
  </DataTemplate>
</UserControl.Resources>

<ItemsControl ItemTemplate="{StaticResource HomeItemTemplate}" />
现在,放置此ItemsControl的视图具有DataContext。在这个数据上下文中,我有我的MyCommand。我必须在多个位置使用此ItemsControl,因此我不想在DataTemplate中直接引用ElementName

我尝试了TemplatedParent和RelativeSource,不同的东西,我不知道我应该做什么。我必须如何编写它,以便我的UserControl可以绑定到ItemsControl的DataContext?

如果资源字典中有DataTemplate/ItemTemplate,则可能需要使用{RelativeSource FindAncestor}绑定模式绑定到父ItemsControl的属性:


MyCommand是否总是同一个命令?不一定。另外,我还有其他需要绑定的属性,这个命令只是一个例子;还请注意,如果在任何非从ItemsControl派生的控件中使用datatemplate,则此绑定将不起作用…已经尝试过,但不起作用。有人告诉我这可能是因为我所在的资源在正常的可视化树之外,对此不确定。不,资源字典中的数据模板不是问题。如果它仍然不起作用,那么问题是与其他资源有关的。那么,字典可能是相关的副作用。有不同的失败可能性,例如ItemsControl的datacontext不是您所期望的,MyCommand属性不是由INotifyPropertyChanged实现支持的,而是在绑定建立后设置的;仅举几个例子。。。
<UserControl.Resources>
  <DataTemplate x:Key="HomeItemTemplate">
    <UserControl Command="{Binding DataContext.MyCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}}}"/>
  </DataTemplate>
</UserControl.Resources>