首页 > Windows开发 > 详细

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

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

一个功能,在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命令实现

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!