Getting started with mvvm-light – RelayCommand<T>

The RelayCommand<T> is similar to the RelayCommand, but allows to directly pass an object to the command. It implements the ICommand interface and can therefore be used to bind to Commands in XAML (e.g. as the Command property of the Button element). You can then use the CommandParameter property to pass the object to the command.

XAML example:

<Button Command="{Binding MyCommand}" CommandParameter="{Binding MyModel}" />

The constructor takes two arguments; the first is an Action which will be executed if ICommand.Execute is called (e.g. the user clicks on the button), the second one is a Func<string,bool> which determines if the action can be executed (defaults to true, called canExecute in the following paragraph).
the basic structure is as follows:

public RelayCommand<string> MyCommand => new RelayCommand<string>(
    obj =>
    {
        //execute action
        Message = obj;
    },
    obj =>
    {
        //return true if button should be enabled or not
        return obj != "allowed";
    }
);

Some notable effects:

  • If canExecute returns false, the Button will be disabled for the user
  • Before the action is really executed, canExecute will be checked again
  • You can call MyCommand.RaiseCanExecuteChanged(); to force reevaluation of the canExecute Func

if you want to reproduce, please indicate the source:
Getting started with mvvm-light – RelayCommand<T> - CodeDay