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