I have a TreeView
setup so that each TreeViewItem
has right-click context menu applied as a Style
. Something like:
<Grid.Resources>
<ContextMenu x:Key="contextMenu">
<MenuItem Header="Save" IsEnabled="{Binding Path=Saveable}"/>
<MenuItem Header="Copy" IsEnabled="{Binding Path=Copyable}"/>
<MenuItem Header="Remove" IsEnabled="{Binding Path=Removeable}"/>
</ContextMenu>
<Style TargetType="TreeViewItem">
<Setter Property="ContextMenu" Value="{StaticResource contextMenu}" />
</Style>
</Grid.Resources>
Saveable, Copyable and Removeable are properties that come from the object that's used as the TreeViewItem
.
What I'm looking for is when the user clicks on a MenuItem
, it would click on the appropriate method of the selected object. So clicking on the "Save" MenuItem
would call object.Save()
, "Copy" calls object.Copy()
, etc. But I'm not sure what the syntax would look like, or whether the idea is actually acceptable in terms of typical WPF style. I know I can just create a new event handler in the encompassing window, but I'd prefer the selected item itself to handle the event.
Thoughts?
Thanks!
Unfortunately, I don't think that there is an automated way of doing this. The closest option would be to setup a RoutedUICommand
for each item in the ContextMenu
, and then create a CommandBinding
for each in your class. If you want those to go to the TreeViewItem
, you'll probably need to subclass TreeViewItem
and set up the CommandBindings
there.
The one option that I thought might work would be to add an EventSetter
for MenuItem.Click
to the TreeViewItem
style. However, that did not work - probably because the items in the ContextMenu
are in a different visual tree from the TreeViewItems
.