第九章 深入浅出话命令
事件的作用是发布、传播一些消息,消息送达接收者,事件的使命也就完成了,每个接收者使用自己的行为来相应事件。事件不具有约束力,命令具有约束力,不仅可以约束代码,还可以约束步骤逻辑。
- 命令:ICommand接口的类,常用的是RoutedCommand类,也可以自定义类。
- 命令源:命令的发送者,ICommandSource接口的类。
- 命令目标:命令发给谁,或者命令作用在谁身上。IInputElement接口的类。
- 命令关联:把一些外围逻辑与命令关联起来,如进行逻辑判断、后续处理等。
示例:用Button发送一个命令,当命令到达TextBox时TextBox会被清空(如果TextBox中没有文字则命令不可被发送)。
<Window x:Class="WpfApplication1_2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Background="LightBlue"
Title="MainWindow" Height="175" Width="260">
<StackPanel x:Name="stackPanel">
<Button x:Name="button1" Content="Send Command" Margin="5"/>
<TextBox x:Name="textBoxA" Margin="5" Height="100"/>
</StackPanel>
</Window>
namespace WpfApplication1_2
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
InitializeCommand();//
}
//声明并定义命令,一处声明、处处使用
private RoutedCommand clear_Cmd = new RoutedCommand("Clear", typeof(MainWindow));
private void InitializeCommand()
{
//把命令赋值给发送者(命令源)并指定快捷键
this.button1.Command = this.clear_Cmd;
this.clear_Cmd.InputGestures.Add(new KeyGesture(Key.C,ModifierKeys.Alt));
//指定命令目标
this.button1.CommandTarget = this.textBoxA;
//创建命令关联
CommandBinding cb = new CommandBinding();
cb.Command = this.clear_Cmd;//只关注与clear_Cmd相关的事件
cb.CanExecute += new CanExecuteRoutedEventHandler(cb_CanExecute);
cb.Executed += new ExecutedRoutedEventHandler(cv_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 ;}

最低0.47元/天 解锁文章
2万+

被折叠的 条评论
为什么被折叠?



