//基本的ICommand
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); clearCmd clcmd = new clearCmd(tb); bt.Command = clcmd; } public class clearCmd : ICommand { TextBox data; public clearCmd(TextBox o) { data = o; } public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } public bool CanExecute(object parameter) { return !string.IsNullOrEmpty(data.Text); } public void Execute(object parameter) { data.Clear(); } }
//路由命令RoutedCommand,本身不包含CanExecute和Executed实际执行逻辑,而是引发逻辑树遍历,查找绑定了了该路由命令的CommandBinding,由CommandBinding实际执行CanExecute和Executed。
public partial class MainWindow : Window { private RoutedCommand clearCmd = new RoutedCommand("Clear", typeof(MainWindow)); public MainWindow() { InitializeComponent(); bt.Command = clearCmd; clearCmd.InputGestures.Add(new KeyGesture(Key.C, ModifierKeys.Alt)); //这是为命令增加快捷键 bt.CommandTarget = tb;//这里为逻辑树遍历起点 CommandBinding cb = new CommandBinding(); cb.Command = clearCmd; cb.CanExecute += Cb_CanExecute; cb.Executed += Cb_Executed; this.CommandBindings.Add(cb); } private void Cb_Executed(object sender, ExecutedRoutedEventArgs e) { tb.Text = ""; e.Handled = true; } private void Cb_CanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = !string.IsNullOrEmpty(tb.Text); e.Handled = true; } }