RelayCommand Implementation

17 Sep 2022

← Home
1 min. read

Commands are a big part of communication between Views and ViewModels in WPF. Below is my current favorite implementation of the RelayCommand:

public class RelayCommand : ICommand
{
    private readonly Action<object> _execute;
    private readonly Predicate<object> _canExecute;

    public event EventHandler CanExecuteChanged
    {
        add => CommandManager.RequerySuggested += value;
        remove => CommandManager.RequerySuggested -= value;
    }

    public RelayCommand(Action execute, Func canExecute = null)
        : this(x => x.execute(), x => canExecute is null || canExecute()) { }

    public RelayCommand(Action<object> execute, Predicate<object> canExecute = null)
    {
        _execute = execute ?? throw new ArgumentNullException(nameof(execute));
        _canExecute = canExecute;
    }

    public bool CanExecute(object parameter) => _canExecute?.Invoke(parameter) ?? true;

    public void Execute(object parameter) => _execute?.Invoke(parameter);
}

Usage

The implementation allows for RelayCommands with/without CanExecute Predicates and handles CommandParameters.

MyCommand = new RelayCommand(OnCommand);
MyCommand = new RelayCommand(OnCommand, CanExecute);
MyCommand = new RelayCommand(commandParam => OnCommand(commandParam));
MyCommand = new RelayCommand(commandParam => OnCommand(commandParam), commandParam => CanExecute(commandParam));