wpfxamlbackgroundrelativesource

How to Bind to a Child's Background in Xaml?


I'm able to bind to a child's Background if the child is explicitly named in ElementName:

<TreeViewItem Header="Test" Background="{Binding ElementName=TestChild, Path=Background}">
   <TextBox Name="TestChild" Text="Hello?" Background="{Binding SomeBinding}" />
</TreeViewItem>

I'd prefer to use relative position rather than specific names. Is it possible to bind to a child using relative? In this case it will always be the first child. The following DOESN'T work but seems like it should.

<TreeViewItem Header="Test" Background="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Children[0].Background}">

Solution

  • Unless you create a new control that inherits from Treeview (or any other itemsControl) this wont work. The reasoning is all to do with the way that binding works. When that binding is set the Children[0] doesn't exist as the collection is empty. after this the collection is updated to include your textbox and doesn't raise a notify that it has changed (its not an ObservableCollection). The only way to do this is to create a new control which has Children as an ObservableCollection. FWIW I dont think its worth the hassle and your better off using ElementName.