I have got one Collection wich contains a Collection itself. Now I want to go through both Collections in wpf. I'm trying to bind the Color Property of the second Collection to a Dependency Property of the first Collection. But until now, I didn't find a way to Bind it Properly. In case of Visibility-Binding I found a work-around by binding the Visibility-Property of the canvas layout in the second ItemsPanelTemplate to the wanted property.
Here's some piece of code which represents my situation:
<ItemsControl x:Name="Itemcntrl10" ItemsSource="{Binding Collection1}" >
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<ItemsControl x:Name="Itemcntrl12" ItemsSource="{Binding Collection2}" >
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas Visibility="{Binding Visibility, Converter={StaticResource BooleanToVisibilityConverter}}" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Line X1="{Binding X}" Y1="{Binding Y}"
X2="{Binding old.X}" Y2="{Binding old.Y}"
StrokeThickness="{Binding Path=DataContext.StrokeThickness, ElementName=ThisMainWindow}"
>
<Line.Stroke>
<SolidColorBrush Color="Black" />
</Line.Stroke>
</Line>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Any ideas how to get this handled ? I thought about ElementBinding to the upper ItemsControl but this didn't solve my problem either.
You can use a RelativeSource
binding to access an item further up the VisualTree
For example,
Color="{Binding RelativeSource={RelativeSource AncestorType={x:Type Canvas}},
Path=DataContext.SomeColorProperty}"
This should look up your VisualTree for the closest Canvas
object, which will be the one used in Itemcntrl12
, and it will bind to it's DataContext
, which should be a data item in your first ItemsControl
.
If you wanted to go up another level and bind to a property of the first ItemsControl
(Itemcntrl10
), you could use the AncestorLevel
property of the binding to specify the 2nd Canvas instead of the first one.