MVVM中的ContextMenu [英] ContextMenu in MVVM

查看:79
本文介绍了MVVM中的ContextMenu的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将上下文菜单绑定到命令列表.

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}" />

contextmenu项的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中的ContextMenu的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆