zoukankan      html  css  js  c++  java
  • 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界面中的元素进行操作。

  • 相关阅读:
    第七周进度总结
    第六周进度总结
    第五周进度总结
    《大道至简》读后感
    第四周进度总结
    第三周进度总结
    第二周进度总结
    第一周进度总结
    top工具
    系统监控的一些工具w , vmstat
  • 原文地址:https://www.cnblogs.com/amourjun/p/6536388.html
Copyright © 2011-2022 走看看