本文共 3014 字,大约阅读时间需要 10 分钟。
参考的是书籍《深入浅出WPF》。运行环境:win10+vs2019。除某些截图中的代码外,其他均已本地测试通过。
命令具有约束性,事件没有。
命令可以约束代码,约束步骤逻辑,方便debug。PreviewCanExecute/CanExecute/PreviewExecuted/Executed都是附加事件,是被CommandManager类附加给命令目标的。前两个执行事件是不受程序猿控制的。
定义一个命令,使用Button发送,当命令到达TextBox时TextBox会被清空。如果TextBox中没有文字,则命令不可被发送。
开始时因为TextBox是空的,所以按钮被禁用。
后台
using System.Windows.Input;namespace pxy{ ////// MainWindow.xaml 的交互逻辑 /// public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); InitializeCommand(); } private RoutedCommand clearCmd = new RoutedCommand("Clear", typeof(MainWindow)); private void InitializeCommand() { this.button1.Command = this.clearCmd; // 指定命令源 // 设置快捷键 this.clearCmd.InputGestures.Add(new KeyGesture(Key.C, ModifierKeys.Alt)); this.button1.CommandTarget = this.textBoxA; // 指定命令目标 //创建命令关联 CommandBinding cb = new CommandBinding(); cb.Command = this.clearCmd; // 只关注与clearCmd相关的事件 cb.CanExecute += new CanExecuteRoutedEventHandler(cb_CanExecute); cb.Executed += new ExecutedRoutedEventHandler(cb_Executed); // 必须把命令关联安置到外围控件上 this.stackPanel.CommandBindings.Add(cb); } void cb_CanExecute(object sender, CanExecuteRoutedEventArgs e) { // 如果TextBox时空的 if (string.IsNullOrEmpty(this.textBoxA.Text)) { e.CanExecute = false; }else { e.CanExecute = true; } e.Handled = true; // 避免继续向上传而降低性能 } void cb_Executed(object sender, ExecutedRoutedEventArgs e) { this.textBoxA.Clear(); e.Handled = true; } } }
包括ApplicationCommands/ComponentCommands/NavigationCommands/MediaCommands/EditingCommands,都是静态类。命令都是这些类的静态只读属性。仍然是单例模式。 如果程序中需要例如Open/Save/Play/Stop等标准命令的话,就不用自己声明了,直接使用命令库。
转载地址:http://nmelz.baihongyu.com/