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