Programmatically raise a command Programmatically raise a command wpf wpf

Programmatically raise a command


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


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.


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

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