[]
        
(Showing Draft Content)

RelayCommand

A RelayCommand is a lightweight implementation of ICommand that allows defining command behavior through delegates without needing to create a new command class for each action. The RelayCommand is the heart of command binding.

This pattern reduces boilerplate code and makes commands easy to define directly in ViewModels or controllers.

It acts as a relay between:

  • The UI control (like a button)

  • The actual logic in your controller or viewmodel (e.g., showing a message)

 public class RelayCommand : ICommand //Implements ICommand Interface
 {
     private readonly Action<object?> _execute;
     private readonly Predicate<object?>? _canExecute;
     public event EventHandler? CanExecuteChanged; //Event for UI Updates
     public RelayCommand(Action<object?> execute, Predicate<object?>? canExecute = null)
     {
         _execute = execute ?? throw new ArgumentNullException(nameof(execute));
         _canExecute = canExecute;
     } //Constructor
     public bool CanExecute(object? parameter) => _canExecute?.Invoke(parameter) ?? true; //Validate before execution
     public void Execute(object? parameter) => _execute(parameter); //Run the command
     public void RaiseCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty); //Refresh UI state
 }

With the RelayCommand, commands are concise, testable, and fully reusable, allowing developers to focus on application logic instead of UI event wiring.