TreeViewItem 上的上下文菜单调用 TreeViewItem 的方法?
我有一个 TreeView
设置,以便每个 TreeViewItem
都有作为 Style
应用的右键单击上下文菜单。 类似于:
<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 和Removeable 是来自用作TreeViewItem
的对象的属性。
我正在寻找的是,当用户单击 MenuItem
时,它将单击所选对象的适当方法。 因此,点击“Save”MenuItem
会调用 object.Save()
,“Copy”会调用 object.Copy()
,等等。但是我不确定语法是什么样子,或者这个想法在典型的 WPF 风格方面是否实际上可以接受。 我知道我可以在包围窗口中创建一个新的事件处理程序,但我更喜欢所选项目本身来处理该事件。
想法?
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不幸的是,我认为没有一种自动化的方法可以做到这一点。 最接近的选项是为 ContextMenu 中的每个项目设置一个 RoutedUICommand,然后为类中的每个项目创建一个 CommandBinding。 如果您希望将它们转到
TreeViewItem
,您可能需要子类化TreeViewItem
并在那里设置CommandBindings
。我认为可能有效的一个选项是将
MenuItem.Click
的EventSetter
添加到TreeViewItem
样式。 但是,这不起作用 - 可能是因为ContextMenu
中的项目与TreeViewItems
位于不同的可视化树中。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 theContextMenu
, and then create aCommandBinding
for each in your class. If you want those to go to theTreeViewItem
, you'll probably need to subclassTreeViewItem
and set up theCommandBindings
there.The one option that I thought might work would be to add an
EventSetter
forMenuItem.Click
to theTreeViewItem
style. However, that did not work - probably because the items in theContextMenu
are in a different visual tree from theTreeViewItems
.