Reputation: 623
I've built a WPF based Treeview with
Item
-Subitem
If Subitem is selected, I would like to display also Properties of Item.
<StackPanel Grid.Column="2" DataContext="{Binding ElementName=myTreeView, Path=SelectedItem}">
<TextBox Text="{Binding Path=Name, Mode=TwoWay}" />
<TextBox Text="{Binding RelativeSource={???} Path=Name, Mode=TwoWay}" />
</StackPanel>
I guess I need to use a RelativeSource statement, but not quite sure how to do so.
Upvotes: 3
Views: 16548
Reputation: 1775
JesseJames has given you the correct way to use RelativeSource but the best you will be able to do with RelativeSource is bind to the TreeViewItem itself, which is just the container for your data object i.e ViewModel, meaning you won't be able to access your data objects properties(easily).
I think in this case binding to the container object would break the View-ViewModel approach you are using. Your best bet would be to create a Parent object within your ViewModel and bind to that object. So that now each object in your collection has a reference to it's parent which can now be bound to directly.
<StackPanel Grid.Column="2" DataContext="{Binding ElementName=myTreeView, Path=SelectedItem}">
<TextBox Text="{Binding Path=Name, Mode=TwoWay}" />
<TextBox Text="{Binding Parent.Name}" />
</StackPanel>
Also note that the SelectedItem property returns your data object and not the container.
Upvotes: 6
Reputation: 3440
I looked at your code, try binding simply to Name
. It appears that your data context should already be set to the TreeViewItem
due to the following line: <StackPanel Grid.Column="2" DataContext="{Binding ElementName=myTreeView, Path=SelectedItem}">
. The RelativeResource
binding is probably looking further up the logical tree and that's why your binding is failing.
Upvotes: 0
Reputation: 5083
{Binding RelativeSource={RelativeSource AncestorType={x:Type typeOfAncestor}}, Path=Name, Mode=TwoWay}
Upvotes: 8