第九章 深入浅出话命令

第九章 深入浅出话命令

事件的作用是发布、传播一些消息,消息送达接收者,事件的使命也就完成了,每个接收者使用自己的行为来相应事件。事件不具有约束力,命令具有约束力,不仅可以约束代码,还可以约束步骤逻辑。

  • 命令: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 ;}

      
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值