Programmatically raise a command

主宰稳场 提交于 2020-11-30 20:40:35

问题


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.


回答1:


Not sure if you mean:

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

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

Mybutton.Command?.Execute(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);



回答2:


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:

CustomCommands.PlaybackPlayPause.Execute(null, null);

passing 2nd parameter as null will call all attached elements.




回答3:


You need ICommand.Execute(object) to accomplish that.

Working example for your sample code: this.MyButton.Command.Execute(null);




回答4:


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:

    if (ApplicationCommands.Open.CanExecute(null, null))
        ApplicationCommands.Open.Execute(null, null);

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.



来源:https://stackoverflow.com/questions/3520713/programmatically-raise-a-command

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!