MVVM 中的上下文菜单 [英] ContextMenu in MVVM
问题描述
我想将上下文菜单绑定到命令列表.
I want to bind a contextmenu to a list of commands.
<Grid.ContextMenu>
<ContextMenu ItemsSource="{Binding ItemContextCommands, Converter={StaticResource commandToStringConverter}}">
<ContextMenu.ItemTemplate >
<DataTemplate DataType="MenuItem">
<MenuItem Command="{Binding}"></MenuItem>
</DataTemplate>
</ContextMenu.ItemTemplate>
</ContextMenu>
</Grid.ContextMenu>
commandToStringConverter
只是将命令列表转换为字符串列表,对列表中的每个命令调用 ToString()
.
The commandToStringConverter
simply converts a list of commands to a list of strings calling the ToString()
on each command in the list.
如何实现每个MenuItem
中的Command
被调用?
How can I achieve that the Command
in each MenuItem
is called?
推荐答案
我会使用一个小的视图模型"来保存这样一个命令的信息.
I would use a small "view model" to hold the informations for such a command.
class ContextAction : INotifyPropertyChanged
{
public string Name;
public ICommand Action;
public Brush Icon;
}
在你的视图模型中创建一个集合,它应该得到像
make a collection inside your view model which should get the context actions like
ObservableCollection<ContextAction> Actions {get;set;}
并简单地将此集合绑定到您的 ContextMenu
.
and simply bind this collection to your ContextMenu
.
<Grid.ContextMenu>
<ContextMenu ItemsSource="{Binding Actions}" />
上下文菜单项的 ItemTemplate
现在可以访问名称、命令以及您可能需要的任何其他内容.更改 CommandParameter
也可能很有用,以便它使用操作拥有元素而不是操作本身调用命令.
The ItemTemplate
for the contextmenu items can now access the name, the command and whatever else you might need. It might be useful to change the CommandParameter
as well so that it will call the command with the actions owning element, not with the action itself.
这篇关于MVVM 中的上下文菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!