为建立中文知识库加块砖 ——中科大胡不归
0. 前言
使用 WPF 久了,迟早会遇上:使用代码将 CheckBox 的 IsChecked 设置为 true,发现绑定的Command没有触发的问题。
1. 代码模拟点击事件
对于按钮可以使用下面的方法实现代码模拟点击事件。
方法一
ButtonAutomationPeer peer = new ButtonAutomationPeer(someButton);
IInvokeProvider invokeProv = peer.GetPattern(PatternInterface.Invoke) as IInvokeProvider;
invokeProv.Invoke();
方法二
someButton.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
然而似乎并不适用CheckBox的情况,所以使用下面的办法直接触发Command。
2. 代码触发绑定的Command
someButton.Command.Execute(someButton.CommandParameter);
网友评论