C# WPF从子ItemsControl数据模板内部绑定到父ItemsControl
我需要能够从子C# WPF从子ItemsControl数据模板内部绑定到父ItemsControl,c#,.net,wpf,binding,C#,.net,Wpf,Binding,我需要能够从子ItemsControl数据模板内部绑定到父ItemsControl的属性: <ItemsControl ItemsSource="{Binding Path=MyParentCollection, UpdateSourceTrigger=PropertyChanged}"> <ItemsControl.ItemTemplate> <DataTemplate> <ItemsContr
ItemsContro
l数据模板内部绑定到父ItemsControl
的属性:
<ItemsControl ItemsSource="{Binding Path=MyParentCollection, UpdateSourceTrigger=PropertyChanged}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<ItemsControl ItemsSource="{Binding Path=MySubCollection}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=MyParentCollection.Value, UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
如何从内部数据模板内部绑定到MyParentCollection.Value?我不能按类型使用FindAncestor,因为所有级别都使用相同的类型。我想也许我可以在外部集合上放置一个名称,并在内部绑定中使用ElementName标记,但这仍然无法解析属性
有什么想法吗 在子项控件的标记中保存父项可能会起作用
<DataTemplate>
<ItemsControl ItemsSource="{Binding Path=MySubCollection}" Tag="{Binding .}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Tag.Value, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</DataTemplate>
它没有经过测试,但给了您一个正确的提示:)不需要另一个答案中建议的
标签的绑定。所有数据都可以从ItemControl的DataContext获得(这个标记Tag=“{Binding}”
只是将DataContext复制到标记属性中,这是多余的)
你不能使用FindAncestor模式,同时指定类型和祖先级别吗?嗯,我甚至没有想到祖先级别……我来看看,我似乎无法实现这一点,哦,今天的好黑客,但还是挽救了这一天。非常感谢你!我希望标记绑定只是引用绑定上下文,而不是复制上下文中的内容。这是一个了不起的黑客!
public class MyChildObject
{
public String Name { get; set; }
}
<DataTemplate>
<ItemsControl ItemsSource="{Binding Path=MySubCollection}" Tag="{Binding .}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Tag.Value, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</DataTemplate>
<ItemsControl ItemsSource="{Binding Path=MyParentCollection}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<ItemsControl ItemsSource="{Binding Path=MySubCollection}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=DataContext.Value, RelativeSource={RelativeSource AncestorType=ItemsControl}}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>