views:

12

answers:

2

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}">
A: 

Try this:

Background="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Items[0].Background}
vc 74
Right after I posted, that occurred to me. I tried it. Alas, it doesn't work either. Thanks anyway.
BSalita
+1  A: 

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.

Leom Burke
I've run some tests. Your answer is consistent with the results. I find that using a Loaded event is a solution. <TreeViewItem Loaded="Test_Loaded" ... and in Test_Loaded, do sender.Background = sender.Items(0).Background
BSalita
Yes - If you want to really avoid naming it in the XAML you can do it in the loaded event. In my view though this is no different to using ElementName (and is more work)
Leom Burke
The advantage to the Loaded event is that all nodes can share the same event. I can paste in the Xaml as opposed to explicitly state each child name.
BSalita
Fair point - although thinking about it your background on the textbox is bound to something so you could bind the treeviewitem to that binding instead and then bind the textbox to it using RelativeSource FindAncestor.
Leom Burke