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.
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....
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With