Implementing Generic ICommand in MVVM with RelayCommand Pattern

Dec 08, 2025 · Programming · 10 views · 7.8

Keywords: C# | .NET | WPF | MVVM | ICommand | RelayCommand

Abstract: This article explores how to simplify ICommand implementation in WPF MVVM using the RelayCommand pattern, which utilizes delegates to avoid repetitive class creation and enhance code reusability and maintainability.

MVVM Pattern and ICommand Interface

In WPF applications, the Model-View-ViewModel (MVVM) pattern is widely adopted to enhance testability and maintainability. The ICommand interface is crucial for implementing the command pattern, allowing view elements like buttons to bind to actions in the ViewModel.

Challenges in Traditional Implementation

Traditionally, each command requires a separate class implementing the ICommand interface, leading to code redundancy and repetitive work.

Solution with Generic Command Class

To simplify this, a generic command class such as RelayCommand can be used. RelayCommand uses delegates to pass CanExecute and Execute methods through the constructor, avoiding the need to create new classes for each command.

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

    public RelayCommand(Predicate<object> canExecute, Action<object> execute)
    {
        _canExecute = canExecute;
        _execute = execute;
    }

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

    public bool CanExecute(object parameter)
    {
        return _canExecute(parameter);
    }

    public void Execute(object parameter)
    {
        _execute(parameter);
    }
}

When used in the ViewModel, the command can be instantiated as follows:

public class MyViewModel
{
    private ICommand _doSomething;
    public ICommand DoSomethingCommand
    {
        get
        {
            if (_doSomething == null)
            {
                _doSomething = new RelayCommand(
                    p => this.CanDoSomething,
                    p => this.DoSomeImportantMethod());
            }
            return _doSomething;
        }
    }
}

Advantages and Implementation Details

The advantages of this approach include concise code, ease of extension, and maintainability. By utilizing CommandManager.RequerySuggested, the CanExecuteChanged event is automatically handled, ensuring that UI elements update their state correctly.

Conclusion

The RelayCommand pattern is an effective way to reduce the complexity of implementing commands in MVVM, promoting code reuse, and is considered a best practice in WPF development.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.