Search code examples
wpfmvvmrelaycommand

How can I invoke relay command with parameter programmatically wpf mvvm?


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


Solution

  • 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);