Bind to Parent Object Property with RelativeSource

14,157

Solution 1

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.

Solution 2

 {Binding RelativeSource={RelativeSource AncestorType={x:Type typeOfAncestor}}, Path=Name, Mode=TwoWay}
Share:
14,157
Stef
Author by

Stef

Updated on June 04, 2022

Comments

  • Stef
    Stef almost 2 years

    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.