• 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界面中的元素进行操作。

  • 相关阅读:
    LIBSVM
    tf-idf
    DIV+CSS例子
    网页背景设置
    获取JDBC中的ResultSet的记录的条数
    SQL 基本语句
    经典SQL语句大全
    JS(截取字符串,显示当前系统时间yyyy-MM-dd,从文本框得到的数值计算)
    JavaScript实现全排列
    Java发送邮件
  • 原文地址:https://www.cnblogs.com/amourjun/p/6536388.html
Copyright © 2020-2023  润新知