命令例子

    <StackPanel x:Name="stackPanel">
        <Button x:Name="button1" Content="Send Command" Margin="5"/>
        <TextBox x:Name="textBoxA" Margin="5,0" Height="100"/>
    </StackPanel>
        public MainWindow()
        {
            InitializeComponent();
            InitializeCommand();
        }
        //声明并定义命令
        private RoutedCommand clearCmd = new RoutedCommand("Clear", typeof(MainWindow));

        private 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;//只关注 与clear相关的事件
            cb.CanExecute += new CanExecuteRoutedEventHandler(cb_CanExcute);
            cb.Executed += new ExecutedRoutedEventHandler(cb_Excuted);

            //把命令关联在外围控件上
            this.stackPanel.CommandBindings.Add(cb);


            //当探测命令是否可以执行时
            void cb_CanExcute(object sender,CanExecuteRoutedEventArgs e)
            {
                if(string.IsNullOrEmpty(this.textBoxA.Text))
                {
                    e.CanExecute = false;
                }
                else
                {
                    e.CanExecute = true;
                }
                //避免继续向上传降低性能
                e.Handled = true;
            }
            //当命令送达后
            void cb_Excuted(object sender,ExecutedRoutedEventArgs e)
            {
                this.textBoxA.Clear();
                e.Handled = true;
            }
        }

1.使用命令可以避免自己写代码判断button是否可用以及添加快捷键

2.RoutedCommand 是一个与业务逻辑无关的类,只负责跑腿并不对命令目标做任何操作,CommandBinding清空的TextBox。

3.CanExcute处理完建议添加e.Handled = true。

4.CommandBinding一定要设置在命令目标的外围控件上。

原文地址:https://www.cnblogs.com/yuejian/p/10518741.html