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

一个功能,在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界面中的元素进行操作。

posted @ 2017-03-11 22:03  amourjun  阅读(2989)  评论(0编辑  收藏  举报