Getting started with mvvm-light – RelayCommand

The RelayCommand implements the ICommand interface and can therefore be used to bind to Commands in XAML (as the Command property of the Button element)

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<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 ICommand MyCommand => new RelayCommand(
    () =>
        //execute action
        Message = "clicked Button";
    () =>
        //return true if button should be enabled or not
        return true;

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 - CodeDay