-1

I know how to invoke relay command without parameter using mvvm pattern, but how to do the same with command with parameter?

4
  • 2
    Please be more specific. Read the How to Ask topics. It would be great if you could provide a minimal reproducible example. Commented 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. Commented Aug 8, 2018 at 15:26
  • Your command is public so just use: viewModel.MyCommand(myParameter); Commented Aug 8, 2018 at 15:35
  • Yes, but how can I invoke that command from ViewModel? Commented Aug 8, 2018 at 15:44

2 Answers 2

0

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

Yes, but how can I invoke that command(with parameter, which is some component on view) programmatically not disturbing mvvm pattern?
@StalkeR you're still not being clear, if you'd posted code instead of img links we might be able to help you. Command handlers are declared in view models, and it sounds like you're trying to call it from the view model layer. So if effect what it sounds like you're asking is "how do i call a function from another function?".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.