你可能会问有了路由事件为什么还要命令系统呢事件的作用是发布传播信息消息送达接受者,事件的使命也就完成了至于如何响应事件送来的消息事件并不做规定他不能让程序统一执行那还能叫命令吗,的确编程工作就算只算使用事件不使用命令程序逻辑也一样可以执行的很好但我们不能阻程序员按自己的习惯去编写代码不如保存事件处理器,程序员们可以写save(),save Handler()。SaveDocument()….这些都符合代码规范但迟早会导致项目无法读懂命令可以帮助我们降低成本,何乐而不为呢
这些基本元素之间的关系体现在使用命令的过程中。命令的使用大概分为如下几步
(1)
创建命令类:即获得一个实现 COmmand接口的类,如果命令与具体业务逻辑无关则使用WPF类库中的 Routed Command类即可。如果想得到与业务逻辑相关的专有命令,则需创建Routed Command(或者 I Command接口)的派生类演示代码
xmins="Http:
//schemas. microsoft com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoftcom/winfx/2006/xaml"title="command’
(2)
Background"LightBlue"Height"175"Width=260">
(3)
(4)
(5)
<Button x:
Name=“button1"Content"Send Command"Margin 5”>>
(6)
<TextBox x:
Name=“textBoxA” Margin="5,0"Height=100"P
(7)
</Stack Panel
(8)
(9)
后台代码为:
(10) public
partial class Window: Window
(11) public
WindowIO
(12) Initialize
Component;
(13) InitializeCommando;
(14) ∥声明并定义命令
(15) te
RoutedCommand clear Cmd=new Routed Command(“Clear”, typeof( window D)
(16) private
void Initialize Commando
(17) ∥把命令赋值给命令源(发送者)并指定快捷键
(18) this,
button1. Command=this clear Cmd
(19) thisclear
Cmd. InputGestures Add(new Key Gesture(Key. C, ModifierKeys. Alt);
(20) ∥指定命令目标
(21) this
button1. Command Target=this, textBoxA;
(22) ∥创建命令关联
(23) CommandBinding
cb=new Command Binding;
(24) cb
Command=thi Isclearand, d
(25) cb
Can Execute += new Can ExecuteRouted EventHandler(cb Can Execute);
(26)
cb
Executed +=new ExecutedRouted EventHandler( cb Executed)∥把命令关联安置在外围控件