主要代碼以下所示:this
/// <summary> /// 聲明並定義命令。 /// </summary> RoutedCommand ClearCommand = new RoutedCommand("Clear", typeof(MainWindow)); /// <summary> /// 初始化命令。崔有來 2014-7-30 06:23:10 /// </summary> 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); } /// <summary> /// 當命令送達目標後執行該方法。崔有來 2014-7-30 06:27:16 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void cb_Executed(object sender, ExecutedRoutedEventArgs e) { this.TextBoxA.Clear(); e.Handled = true; } /// <summary> /// 當探測命令是否可執行時調用該方法。崔有來 2014-7-30 06:26:20 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void cb_CanExecute(object sender, CanExecuteRoutedEventArgs e) { if (string.IsNullOrEmpty(this.TextBoxA.Text) == true) e.CanExecute = false; else e.CanExecute = true; e.Handled = true; }