Reputation: 6840
I have the following context menu declared in my application resources, and it is referenced by several tree views in my app. I am trying to send the TreeView's SelectedItem property as the command parameter.
The problem is that I can't figure out how to get the commands to send the TreeView's SelectedItem.
The parameter is always null. I have tried using relative sources, templated parents, etc.; as well as, looking for a target of treeview, treeviewitem, and simply the datacontext. I have also tried sending different properties of these items (not just the TreeView's SelectedItem). I can't seem to get it to resolve anything.
<Application.Resources>
<ContextMenu x:Key="ContextMenu.TreeView">
<MenuItem
Header="Add Node"
Command="{Binding AddNodeCommand}"
CommandParameter="{Binding Path=SelectedItem, RelativeSource={RelativeSource AncestorType={x:Type TreeView}}}"></MenuItem>
<MenuItem
Header="Delete Node"
Command="{Binding DeleteNodeCommand}"
CommandParameter="{Binding Path=SelectedItem,RelativeSource={RelativeSource AncestorType={x:Type TreeView}}}"></MenuItem>
</ContextMenu>
</Application.Resources>
<UserControl ...>
<TreeView
x:Name="TaxonomyTree"
ItemsSource="{Binding Path=Tree}"
ContextMenu="{StaticResource ContextMenu.TreeView}"/>
</UserControl>
Upvotes: 1
Views: 663
Reputation: 17380
Try:
<ContextMenu x:Key="ContextMenu.TreeView">
<MenuItem Command="{Binding AddNodeCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type ContextMenu}},
Path=PlacementTarget.SelectedItem}"
Header="Add Node" />
<MenuItem Command="{Binding DeleteNodeCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type ContextMenu}},
Path=PlacementTarget.SelectedItem}"
Header="Delete Node" />
</ContextMenu>
Contextmenu
is not part of the same Visual tree as the TreeView
it links against. So we need to use the PlacementTarget
to route to the TreeView
accordingly.
Upvotes: 1