将contextMenu命令绑定到viewmodel类中的命令 [英] Bind a contextMenu command to a command in viewmodel class

查看:117
本文介绍了将contextMenu命令绑定到viewmodel类中的命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将拥有一个树形视图,当右键单击该树形视图时会显示一个包含多个项目的ContextMenu.我还具有MainWindowViewModel类,该类充当程序运行时生成的窗口的数据上下文.有谁知道如何将ContextMenu MenuItem的命令绑定到该viewmodel类的ICommand成员?我希望能够通过此菜单添加/删除树节点.

谢谢

I would have a treeview that when right clicked on brings up a ContextMenu with several items. I also have a MainWindowViewModel class that serves as the data context for the window that gets generated when the program is run. Does anyone know how to bind the command of a ContextMenu MenuItem to an ICommand member of that viewmodel class? I would like to be able to add/delete tree nodes via this menu.

Thanks

推荐答案

我通过为ContextMenu的事件处理程序手动将我的contextMenu的数据上下文设置为与主窗口相同的方式来欺骗我已打开"事件.

这是MainWindow.xaml.cs中的代码:

I kind of cheated by manually setting my contextMenu''s datacontext to the same one the mainwindow was using by creating an event handler for the ContextMenu''s "Opened" event.

Here''s the code from MainWindow.xaml.cs:

private void ContextMenu_Opened(object sender, System.Windows.RoutedEventArgs e)
        {
            ContextMenu menu = sender as ContextMenu;
            menu.DataContext = DataContext;
        }


这篇关于将contextMenu命令绑定到viewmodel类中的命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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