第9章 深入浅出话命令
9.1 命令系统的基本元素与关系
9.1.1 命令系统的基本元素
- 命令(Command):WPF的命令实际上就是实现了ICommand接口的类,平时使用最多的是RoutedCommand类。
- 命令源(Command Source):即命令的发送者,是实现了ICommandSource接口的类。很多界面元素都实现了这个接口。
- 命令目标(Command Target):即命令将发送给谁,或者说命令将作用在谁身上。命令目标必须是实现了IInputElement接口的类。
- 命令关联(Command Binding):负责把一些外围逻辑与命令关联起来,比如执行之前对命令是否可以执行进行判断、命令执行之后还有哪些后续工作等。
9.1.2 基本元素之间的关系
(1) 创建命令类:即获得一个实现ICommand接口的类,如果命令与具体业务逻辑无关则使用WPF类中的RoutedCommand类即可。如果想得到与业务逻辑相关的专有命令,则需创建RoutedCommand(或者ICommand接口)的派生类。
(2) 声明命令实例:使用命令时需要创建命令类的实例。一般情况下程序中某种操作只需要一个命令实例与之对应即可。因此程序中的命令多使用单件模式(Singleton Pattern)以减少代码的复杂度。
(3)指定命令的源:即指定由谁来发送这个命令。
(4)指定命令目标:命令目标并不是命令的属性而是命令源的属性,指定命令目标是告诉命令源向哪个组件发送命令,无论这个组件是否拥有焦点它都会收到这个命令。如果没有为命令源指定命令目标,则WPF系统认为当前拥有焦点的对象就是命令目标。
(5)设置命令关联 WPF命令需要CommandBinding在执行前来帮助判断是不是可以执行,而执行后做一些事件来“打扫战场”。
命令API关系图:
9.1.3 小试命令
<StackPanel x:Name="stackPanel">
<Button x:Name="button1" Content="Send Command" Margin="5"/>
<TextBox x:Name="textBoxA" Margin="5,0" Height="100"/>
</StackPanel>
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private RoutedCommand clearCmd = new RoutedCommand("Clear", typeof(MainWindow));
public MainWindow()
{
InitializeComponent();
InitializeCommand();
}
public 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;
cb.CanExecute += new CanExecuteRoutedEventHandler(this.cb_CanExecute);
cb.Executed += new ExecutedRoutedEventHandler(this.cb_Executed);
//把命令关联安置在外围控件上
this.stackPanel.CommandBindings.Add(cb);
}
void cb_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
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;
}
}