WPF binding to parent ItemsControl from inside ItemsControl child data item

Ok, so I have funky ones here ... I need to be able to bind to the parent properties of the ItemsControl from within the child DataControl data template:

<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> 

Suppose MyParentCollection (external collection) is of the following type:

 public class MyObject { public String Value { get; set; } public List<MyChildObject> MySubCollection { get; set; } 

And suppose that MyChildObject from the specified class is of the following type:

 public class MyChildObject { public String Name { get; set; } } 

How can I bind to MyParentCollection.Value from an internal data template? I cannot use the FindAncestor type by type because both levels use the same types. I thought that maybe I can put the name in an external collection and use the ElementName tag in the internal binding, but this still cannot solve the property.

Any thoughts? I'm stuck on this ...

+11
source share
2 answers

saving parent element in child tag may work

  <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> 

they didnโ€™t check it, but give a hint in the right direction :)

+17
source

A binding for Tag , as suggested in another answer, is not required. All data can be obtained from the DataContext ItemControl (and this Tag="{Binding}" markup simply copies the DataContext into the Tag property, which is redundant).

 <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> 
0
source

Source: https://habr.com/ru/post/947634/


All Articles