以编程方式发出命令
我有一个按钮:
<Button x:Name="MyButton" Command="SomeCommand"/>
有没有办法从源代码执行命令?调用按钮上的单击没有帮助:
MyButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
我的意思是 - 这确实会引发事件,但不会引发命令。是否有类似于此 RaiseEvent
但仅用于 Command 的东西?如果没有 - 我如何实例化ExecutedRoulatedEventArgs
?是否可以?
最后 - 请不要告诉我如何避免
调用该命令。
I have a button:
<Button x:Name="MyButton" Command="SomeCommand"/>
Is there a way to execute the command from source? Calling the click on the button does not help:
MyButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
I mean - this does raise the event, but it does not raise the command. Is there something similar to this RaiseEvent
but just for Command? If there is not - how can I instantiate ExecutedRoutedEventArgs
? Is it possible?
Lastly - please do not tell me how to avoid
calling the command.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我更喜欢的方法是按照 Sean Sexton 在 以编程方式执行命令
简而言之,找到该命令,检查它是否可以执行,如果可以,则执行。
示例:
为什么我认为它更好:
我认为这是最好的方法,因为它将真正使用正确的路径,并且您不依赖于命名任何控件。另外,虽然您现在知道您不使用“CanExecute”,但您永远不知道将来何时有人会为其添加行为。
My prefered way to do it is to do as Sean Sexton recommend in Executing a Command Programmatically
In short, find the command, check if it can execute and if so, execute.
Example:
Why I think it is better:
I think it's the best way because it will really use the proper path and you do not depends on naming any control. Also, although you know now that you don't use "CanExecute", you never know when somebody will add a behavior for it in the future.
您需要 ICommand.Execute(object) 来完成此任务。
示例代码的工作示例:
this.MyButton.Command.Execute(null);
You need
ICommand.Execute(object)
to accomplish that.Working example for your sample code:
this.MyButton.Command.Execute(null);
或者,如果您无权访问 UI 元素,则可以直接调用静态命令。例如,我在 App.xaml 中有一个系统范围的键钩子,并且想要调用我的播放/暂停/停止等媒体事件:
将第二个参数传递为 null 将调用所有附加元素。
Or if you don't have access to the UI element you can call the static command directly. For example I have a system wide key hook in
App.xaml
and wanted to call my play/pause/stop etc media events:passing 2nd parameter as null will call all attached elements.
不确定您的意思是否是:
对于 c#6 及更高版本(由 eirik 提议),有简短的形式:
更新
正如 @Benjol 所提议的,在某些情况下可能需要提供按钮的
CommandParameter
属性值,并且添加它而不是null
可能会被视为默认值图案:Not sure if you mean:
with c#6 and later (as proposed by eirik) there is the short form:
Update
As proposed by @Benjol, providing the button's
CommandParameter
-property value can be required in some situations and the addition of it instead ofnull
may be considered to be used as the default pattern: