将 ContextMenu 项动态绑定到静态定义的 MenuItems [英] Dynamically binding ContextMenu items to statically defined MenuItems
问题描述
我的应用程序包含一个 TreeView
,它支持一组命令,但命令可能会在菜单之间移动,只出现在某些菜单上而不出现在其他菜单上,在多个菜单之间共享等.>
我知道我在编译时支持的所有命令的集合,所以理论上我可以定义一个带有 x:Key
属性的 资源它们都在我的
部分.但是,对于单击的任何给定节点,出现的菜单项只能在运行时确定.我可以将 ContextMenu.ItemsSource
绑定到我的应用程序中返回 MenuItem[]
的东西,但是为了构建这个数组,我需要访问在 XAML 文件中静态定义.
我做错了吗?或者有没有办法做我想做的事?
绑定你的 ContextMenu.ItemsSource 不是 MenuItem[] 而是 ObservableCollection
你的菜单类 >.YourMenuClass 应该包含您想要绑定到的标题和其他参数,可能是一个命令.然后使用模板生成您的菜单项.
<ContextMenu.ItemTemplate><数据模板><MenuItem Header="{Binding Path=Name}" Command="{Binding MyCommand}"/></数据模板></ContextMenu.ItemTemplate></ContextMenu>
My application contains a TreeView
which supports a set of commands, but the commands might move around between menus, only appear on some menus and not others, be shared across multiple menus, etc.
I know the set of all commands that I support at compile time, so in theory I can define a <MenuItem>
resource with an x:Key
attribute for each of them in my <TreeView.Resources>
section. However, for any given node that is clicked, which menu items that appear can only be determined at runtime. I can bind ContextMenu.ItemsSource
to something in my application that returns a MenuItem[]
, but in order to build this array, I would then need to access the MenuItems that were defined statically back in the XAML file.
Am I doing this all wrong? Or is there a way to do what I want?
Bind your ContextMenu.ItemsSource not to a MenuItem[] but a ObservableCollection < YourMenuClass >. YourMenuClass should contain the header and other parameters you want to bind to, maybe a command. Then use a template to generate your menuitems.
<ContextMenu ItemsSource="{Binding MenuItemList}">
<ContextMenu.ItemTemplate>
<DataTemplate>
<MenuItem Header="{Binding Path=Name}" Command="{Binding MyCommand}" />
</DataTemplate>
</ContextMenu.ItemTemplate>
</ContextMenu>
这篇关于将 ContextMenu 项动态绑定到静态定义的 MenuItems的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!