Rob*_*etz 11 .net c# wpf binding
好的,所以我在这里有一个时髦的...我需要能够从子ItemsControl数据模板内部绑定到父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>
Run Code Online (Sandbox Code Playgroud)
我们假设MyParentCollection(外部集合)具有以下类型:
public class MyObject
{
public String Value { get; set; }
public List<MyChildObject> MySubCollection { get; set;
}
Run Code Online (Sandbox Code Playgroud)
我们假设上面的类中的MyChildObject属于以下类型:
public class MyChildObject
{
public String Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
如何从内部数据模板内部绑定到MyParentCollection.Value?我不能真正按类型使用FindAncestor,因为它们都使用相同的类型.我想也许我可以在外部集合上添加一个名称,并在内部绑定中使用ElementName标记,但仍然无法解析该属性.
有什么想法吗?我被困在这一个......
bli*_*eis 17
将子项目保存在子项目控件的标记中可以正常工作
<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>
Run Code Online (Sandbox Code Playgroud)
它未经测试,但给你一个正确方向的提示:)
Tag正如另一个答案中所建议的那样,不需要绑定 for 。所有数据都可以从ItemControl的DataContext中获取(而且这个标记Tag="{Binding}"只是将DataContext复制到了Tag属性中,这是多余的)。
<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>
Run Code Online (Sandbox Code Playgroud)