Is the context menu in a TreeViewItem calling the TreeViewItem method?
I have a setting TreeView
so that each TreeViewItem
has a context menu context menu used as Style
. Sort of:
<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>
Save, copy and delete are properties that come from the object that was used as TreeViewItem
.
I'm looking for when the user clicks on MenuItem
, he clicks on the corresponding method of the selected object. Therefore, clicking on the "Save" button MenuItem
will trigger calls object.Save()
, "Copy" object.Copy()
, etc. But I'm not sure what the syntax would look like, or the idea is really acceptable in terms of typical WPF style. I know I can just create a new event handler on the enclosing window, but I'd rather have the selected item handle the event itself.
Thoughts?
Thanks!
a source to share
Unfortunately, I don't think there is an automated way to do this. The closest option would be to set RoutedUICommand
for each element in ContextMenu
and then create CommandBinding
for each of your classes. If you want them to go in TreeViewItem
, you probably need to subclass TreeViewItem
and customize there CommandBindings
.
One option I thought might work is to add EventSetter
for MenuItem.Click
to the style TreeViewItem
. However, it didn't work - perhaps because the elements in ContextMenu
are in a different visual tree from TreeViewItems
.
a source to share