WPF之Command基础

2025-11-09 07:41:25

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 CanExecuteRoutedEventHandler(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。
猜你喜欢