WPF使用RoutedCommand自定义命令

时间:2022-03-10 15:03:59

主要代码如下所示:

/// <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;
}