Reputation: 13184
In my WPF TreeView, I have defined a HierarchicalDataTemplate
. In its ItemTemplate
, there is a button whose Command
I need to bind to the parent ViewModel, this is the DataContext
of the parent HierarchicalDataTemplate
or, in other words, the ViewModel which holds the collection SubItems
in the example below. The ItemTemplate
s own DataContext
- the SubItem - is to be used as the CommandParameter
.
<TreeView ItemsSource="{Binding Items}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding SubItems}">
<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate>
<Button Command="??CmdOnDtaCntxtOfHierDtaTmplt"
CommandParameter="{Binding}" />
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
How can this be done in XAML only?
Upvotes: 2
Views: 2767
Reputation: 35544
The following binding should work:
<Button Command="{Binding DataContext.Command,
RelativeSource={RelativeSource AncestorLevel=2, AncestorType=TreeViewItem}}"
CommandParameter="{Binding}" />
This will bind to the Command property of the DataContext (in your case the VM that holds the collection SubItems) associated to the TreeViewItem that is the parent of the current TreeViewItem.
Upvotes: 3