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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM