Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically raise a command

Tags:

command

wpf

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.

like image 268
Jefim Avatar asked Aug 19 '10 10:08

Jefim


People also ask

How do you call ICommand from code?

You can call the ICommand. Execute() method. Here is a small example from a project I have.... You can call the command with code like this....

What is the use of ICommand in WPF?

Commands provide a mechanism for the view to update the model in the MVVM architecture. Commands provide a way to search the element tree for a command handler.

What is a binding command?

bind command is Bash shell builtin command. It is used to set Readline key bindings and variables. The keybindings are the keyboard actions that are bound to a function. So it can be used to change how the bash will react to keys or combinations of keys, being pressed on the keyboard.

What is command binding in WPF?

The command is the action to be executed. The command source is the object which invokes the command. The command target is the object that the command is being executed on. The command binding is the object which maps the command logic to the command.


2 Answers

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); 
like image 151
HCL Avatar answered Sep 21 '22 13:09

HCL


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.

like image 27
Dominic Avatar answered Sep 17 '22 13:09

Dominic