以编程方式发出命令 [英] Programmatically raise a command

查看:39
本文介绍了以编程方式发出命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个按钮:

<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));

我的意思是-这确实引发了事件,但没有引发命令.是否有与此 RaiseEvent 类似的东西,仅用于Command?如果没有-如何实例化 ExecutedRoutedEventArgs ?有可能吗?

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.

推荐答案

不确定您的意思是

if(MyButton.Command != null){
    MyButton.Command.Execute(null);
}

在c#6及更高版本(由eirik提出)中,有一种缩写形式:

with c#6 and later (as proposed by eirik) there is the short form:

Mybutton.Command?.Execute(null);

更新
正如@Benjol所建议的那样,在某些情况下可能需要提供按钮的 CommandParameter -property值,并且可以将其添加而不是 null 视为默认值.模式:

Update
As proposed by @Benjol, providing the button's CommandParameter-property value can be required in some situations and the addition of it instead of null may be considered to be used as the default pattern:

Mybutton.Command?.Execute(MyButton.CommandParameter);

这篇关于以编程方式发出命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆