WPF之Command基础

2025-04-22 04:14:09

1、界面布局,文本框和按钮

WPF之Command基础
WPF之Command基础

2、声明并定义命令private RoutedCommand sayCmd = new RoutedCommand("Say", typeof(MainWindow));

WPF之Command基础

3、指定命令的源(命令的发送者)myBtn.Command = sayCmd;

4、指定快捷键sayCmd.InputGestures.Add(new KeyGesture(Key.S, ModifierKeys.Alt));

5、指定命令目标myBtn.CommandTarget = myText;

6、创建命令关联CommandBinding cb = new CommandBinding猾诮沓靥();cb.Command = sayCmd;cb.CanExecute += new C锾攒揉敫anExecuteRoutedEventHandler(cb_CanExecute);cb.Executed += new ExecutedRoutedEventHandler(cb_Executed);

7、把命令关联安置在外围控件上grd.CommandBindings.Add(cb);

WPF之Command基础

8、命令可执行逻辑e.CanExecute = myText.Text.ToString() == "" ? false : true;

WPF之Command基础

9、执行命令MessageBox.Show(myText.Text);

WPF之Command基础

10、执行效果如下

WPF之Command基础
WPF之Command基础
声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢