-1

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

https://i.stack.imgur.com/o7r5i.jpg
https://i.stack.imgur.com/zNkYR.jpg
https://i.stack.imgur.com/lmw3w.jpg
https://i.stack.imgur.com/iJnF0.jpg
StalkeR
  • 13
  • 3
  • 2
    Please be more specific. Read the [ask] topics. It would be great if you could provide a [mcve]. – dymanoid Aug 08 '18 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 Aug 08 '18 at 15:26
  • Your command is public so just use: viewModel.MyCommand(myParameter); – Dipen Shah Aug 08 '18 at 15:35
  • Yes, but how can I invoke that command from ViewModel? – StalkeR Aug 08 '18 at 15:44

2 Answers2

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.

Peregrine
  • 4,287
  • 3
  • 17
  • 34
  • Yes, but how can I invoke that command(with parameter, which is some component on view) programmatically not disturbing mvvm pattern? – StalkeR Aug 08 '18 at 15:33
  • @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?". – Mark Feldman Aug 08 '18 at 22:14
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);

Also, please do not post images of code, but rather your code formatted using the code style.

Mark Diedericks
  • 331
  • 1
  • 9