Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Binding WPF TreeView TreeViewNode to Parent ViewModel

0.00/5 (No votes)
2 Aug 2017 1  
Fairly straight forward way of binding in a HierarchicalDataTemplate or DataTemplate to the parent ViewModel when using the TreeView control.

Introduction

I had a simple situation when using a TreeView control that had the ability to add or remove nodes. The adding was no problem since the template having the button would be adding an element to the ItemsSource of the ViewModel it was bound to, and so the ICommand property for the Command attribute of the Add Button would be on the bound ViewModel. However, the Delete Button would have to remove an element from the ItemsSource of the parent ViewModel. The simple choice was to have a reference to the parent in each ViewModel, but I did not really like that solution. More optimally, I thought, was to bind the Delete Button to an ICommand method in the parent ViewModel.

I know the basics of how to do it, but, as usual, need to use the web to find out the specifics.

The Binding to Parent TreeViewItem DataContext

To bind to the parent ViewModel, you must first bind to the parent Control, which is a TreeViewItem. To do this, you need to use the ReletiveSouce Binding attribute with the FindAncestor Mode. Of course, the AncestorType is TreeViewItem, but need to also use the AncestorLevel of 2 because otherwise FindAncestor would just find TreeViewItem that the Control is contained within.

Command="{Binding DataContext.DeleteAnswer,
          RelativeSource={RelativeSource Mode=FindAncestor,
          AncestorType={x:Type TreeViewItem},
          AncestorLevel=2}}"

You will also notice that you have to use a Path that contains the DataContext and the name of the property that needs to be bound to. That is because the Relative source just finds the TreeViewItem and still you need to specify that you need to bind to the DataContext of the TreeViewItem.

The Sample

The sample only uses a single HierarchicalDataTemplate which has two buttons on it, one to add a TreeViewNode under the HierarchicalDataTemplate node and one to delete the HierarchicalDataTemplate TreeViewNode. The Delete Button is the Button that uses the RelativeSource binding defined in this tip since the Delete Button needs to delete the TreeViewNode from its parent TreeViewNode.

History

  • 08/02/2017: Initial version

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here