主要代码如下所示:
////// 声明并定义命令。/// RoutedCommand ClearCommand = new RoutedCommand("Clear", typeof(MainWindow));////// 初始化命令。崔有来 2014-7-30 06:23:10/// void InitializeCommand(){ // 为命令设置快捷键。 this.ClearCommand.InputGestures.Add(new KeyGesture(Key.C, ModifierKeys.Alt)); // 将命令赋给命令源。 this.Button1.Command = this.ClearCommand; // 指定命令目标。 this.Button1.CommandTarget = this.TextBoxA; // 创建命令关联并安置在外围控件上。 CommandBinding cb = new CommandBinding(); cb.Command = this.ClearCommand; cb.CanExecute += new CanExecuteRoutedEventHandler(cb_CanExecute); cb.Executed += new ExecutedRoutedEventHandler(cb_Executed); this.StackPanel1.CommandBindings.Add(cb);}////// 当命令送达目标后执行该方法。崔有来 2014-7-30 06:27:16/// /// /// void cb_Executed(object sender, ExecutedRoutedEventArgs e){ this.TextBoxA.Clear(); e.Handled = true;}////// 当探测命令是否可执行时调用该方法。崔有来 2014-7-30 06:26:20/// /// /// void cb_CanExecute(object sender, CanExecuteRoutedEventArgs e){ if (string.IsNullOrEmpty(this.TextBoxA.Text) == true) e.CanExecute = false; else e.CanExecute = true; e.Handled = true;}