WPF 命令

介绍

WPF命令系统由几个基本要素构成:

1)命令

WPF命令实际上就是实现了ICommand接口的类,平时使用最多的是RoutedCommand类。

2)命令源

即命令的发送者,是实现了ICommandSource接口的类。很多界面元素都实现了这个接口,其中包括Button、MenuItem等。

3)命令目标

即命令发送给谁,或者说命令将作用在谁身上。命令目标必须实现了IInputElement接口的类。

4)命令关联

负责把一些外围逻辑与命令关联起来,比如执行之前对命令是否可以执行判断、命令执行之后还有哪些后续工作等。

1.界面

 <StackPanel x:Name="stackPanel">
        <Button x:Name="button1" Content="Send Command " Margin="5"/>
        <TextBox x:Name="textBoxA" Margin="5,0" Height="100"/>
    </StackPanel>

2.代码如下

public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            InitCommand();
        }

        // 声明并定义命令
        private RoutedCommand clearCmd = new RoutedCommand("Clear", typeof(MainWindow));
        private void InitCommand()
        {
            // 把命令赋值给命令源(发送者)关指定快捷键
            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; // 只关注与clearCmd相关事件
            cb.CanExecute += new CanExecuteRoutedEventHandler(cb_CanExecute);
            cb.Executed += new ExecutedRoutedEventHandler(cb_Executed);

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

        private void cb_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            this.textBoxA.Clear();
            e.Handled = true;
        }

        // 当探测命令是否可以执行时,此方法被调用
        private void cb_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(this.textBoxA.Text))
            {
                e.CanExecute = false;
            }
            else
            {
                e.CanExecute = true;
            }
            // 避免继续向上传而降低程序性能
            e.Handled = true;
        }
    }

3.显示效果

Alt+C 或点击Send Command 清除文本

猜你喜欢

转载自blog.csdn.net/zang141588761/article/details/83780685