码迷,mamicode.com
首页 > Windows程序 > 详细

WPF--鼠标右键菜单中的Command命令实现

时间:2017-03-11 23:48:45      阅读:364      评论:0      收藏:0      [点我收藏+]

标签:listview   命令   方式   menu   void   bin   右键   --   tar   

一个功能,在ListView中的ListBoxItem控件上实现右键菜单关闭选项,将该ListBoxItem从ListView中删除。

利用 RoutedCommand类创建Command命令,MSDN上将其定义为一个实现 ICommand 并在元素树之内进行路由的命令。

 

C#代码:

 private RoutedCommand closeCmd = new RoutedCommand("Clear", typeof(MainWindow));
private void ListBoxItem_MouseRightButtonUp(object sender,MouseButtonEventArgs e)
        {
            
                ListBoxItem data = new ListBoxItem();
                data = (ListBoxItem)sender;
                
                MenuItem close = new MenuItem();
                close.Header = "删除";

                //声明Mycommand实例                
                close.Command = closeCmd;
                closeCmd.InputGestures.Add(new KeyGesture(Key.D, ModifierKeys.Alt));   //添加快捷键
                close.CommandTarget = data;   //命令作用目标

                CommandBinding cb = new CommandBinding();
                cb.Command = closeCmd;
                cb.CanExecute += cb_CanExecute;
                cb.Executed += cb_Executed;
                data.CommandBindings.Add(cb);
                 
                data.ContextMenu = new ContextMenu();
                data.ContextMenu.Items.Add(close);
                data.ContextMenu.IsOpen = true; 
            
        }

        private void cb_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            ListBoxItem obj =(ListBoxItem)sender;
            this.listView.Items.Remove(obj);
            e.Handled = true;
        }

        private void cb_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            
            e.CanExecute = true;
            e.Handled = true;
        }

 

Command的其他实现方式可根据情况选择使用,这种实现方式方便于对UI界面中的元素进行操作。

WPF--鼠标右键菜单中的Command命令实现

标签:listview   命令   方式   menu   void   bin   右键   --   tar   

原文地址:http://www.cnblogs.com/amourjun/p/6536388.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!