I know how to invoke relay command without parameter using mvvm pattern, but how to do the same with command with parameter?
-
2Please be more specific. Read the How to Ask topics. It would be great if you could provide a minimal reproducible example.dymanoid– dymanoid2018-08-08 15:10:59 +00:00Commented Aug 8, 2018 at 15:10
-
I have a text editor, when I click a button I want to validate text in ViewModel, so command sends text editor object to ViewModel where it is going to be validated. In some case I need to invoke that command programmatically, but I don`t have reference on text editor object because of mvvm pattern.StalkeR– StalkeR2018-08-08 15:26:58 +00:00Commented Aug 8, 2018 at 15:26
-
Your command is public so just use: viewModel.MyCommand(myParameter);Dipen Shah– Dipen Shah2018-08-08 15:35:28 +00:00Commented Aug 8, 2018 at 15:35
-
Yes, but how can I invoke that command from ViewModel?StalkeR– StalkeR2018-08-08 15:44:18 +00:00Commented Aug 8, 2018 at 15:44
2 Answers
If I understand you correctly, your command requires you to pass the TextEditor object in as a parameter, and you'd like to know how to do this in XAML. Since your TextEditor is named XMLView you'd simply bind this to the command parameter;
<KeyBinding Command="{Binding ValidateXMLCommand}" CommandParameter="{Binding ElementName=XMLView}" Modifiers="Control" Key="V" />
Notice the addition of CommandParameter="{Binding ElementName=XMLView}", this will pass the AvalonEdit TextEditor control instance as a parameter of the command.
Read more; https://stackoverflow.com/a/32064646/8520655
If you instead mean to invoke the RelayCommand from a ViewModel (in normal C#), you'd do the following;
if (ValidateXMLCommand.CanExecute(XMLView))
ValidateXMLCommand.Execute(XMLView);
Comments
The control (e.g. Button / MenuItem) that you're binding your relaycommand to will have a CommandParameter property in addition to the Command property.
See here for an example of usage.
To execute a command from code behind, just call its Invoke() method, with the required parameter.