命令与事件类似,事件用来发布传播一些消息,消息到达接收者,事件的使命就完成了,至于如何响应事件送来的消息事件并不做规定;而命令一旦发出,所有的命令目标都必须执行这个命令,二者的区别就在命令具有约束力而事件没有。
命令的基本元素:
命令的使用步骤:
一个UI组件一旦被命令源盯上,命令源就会不停地向命令目标“投石问路”,命令目标也会不停地发送出可路由的CanExcute附加事件,事件沿着UI元素树向上传递并被命令关联捕捉,命令关联捕捉到这些事件后会把命令能不能发送实时报告给命令。
如果命令被发送出去并到达命令目标,命令目标就会发送Excute附加事件,事件沿着UI元素树向上传递并被命令关联捕捉,命令关联会完成指定的后续任务。
现在我们实现这样一个需求,定义一个命令,使用Button来发送这个命令,当命令到达TextBox时,TextBox的文本会被清空,如果TextBox文本为空则命令不可发送,XAML代码如下:
<Window x:Class="WpfApplication7.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <StackPanel x:Name="stackpanel"> <TextBox x:Name="textBox1" Height="23" Margin="10"></TextBox> <Button x:Name="button1" Content="发送命令" Height="23" Margin="10"></Button> </StackPanel> </Window>
后台处理代码如下:
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); InitCmd(); } private RoutedCommand clearCmd = new RoutedCommand("Clear", typeof(MainWindow)); private void InitCmd() { //指定命令源、绑定快捷键 this.button1.Command = clearCmd; this.clearCmd.InputGestures.Add(new KeyGesture(Key.C, ModifierKeys.Alt)); //指定命令目标 this.button1.CommandTarget = textBox1; //创建命令关联 CommandBinding cb = new CommandBinding(); cb.Command = this.clearCmd; cb.Executed += cb_Executed; cb.CanExecute += cb_CanExecute; //把命令关联安置到外围控件 this.stackpanel.CommandBindings.Add(cb); } void cb_CanExecute(object sender, CanExecuteRoutedEventArgs e) { if (string.IsNullOrEmpty(this.textBox1.Text)) e.CanExecute = false; else e.CanExecute = true; //避免继续向上传而降低程序性能 e.Handled = true; } void cb_Executed(object sender, ExecutedRoutedEventArgs e) { this.textBox1.Clear(); e.Handled = true; } }
可见,使用命令就不需要自己写代码判断Button是否可用,CanExcute事件触发频率比较高,为了避免降低性能,在处理完后需要把e.handled设置为ture;CommandBinding一定要设置在命令目标的外围控件上,不然无法捕捉到CanExcute和Excute事件。
原文:http://www.cnblogs.com/yijiaoyingbi/p/4881916.html