C# / .NET Compendium PLEN
.NET / C# / WPF

ICommand in WPF

The problem ICommand solves

In code-behind (the approach without MVVM) handling a click looks like this:

<Button Content="Zapisz" Click="SaveButton_Click" />
private void SaveButton_Click(object sender, RoutedEventArgs e)
{
    SaveOrder();
}

This works, but it breaks MVVM - the View (code-behind) directly contains business logic, the ViewModel has no way to test it without the UI, and Click is an ordinary .NET event, so it is hard to, for example, automatically disable the button when the action makes no sense (e.g. no data to save).

ICommand is an interface that lets you bind a UI action (a click, a keyboard shortcut, a menu item) directly to a method in the ViewModel, without any code-behind, and adds built-in support for "is this action available right now at all".

The interface definition

public interface ICommand
{
    void Execute(object parameter);
    bool CanExecute(object parameter);
    event EventHandler CanExecuteChanged;
}

Three elements: - Execute - what happens when the command is invoked (the equivalent of the body of a Click handler) - CanExecute - whether the command is currently available (returns bool) - WPF automatically greys out/enables the control based on it - CanExecuteChanged - an event telling WPF "check CanExecute again, something may have changed"

Binding in XAML

<Button Content="Zapisz" Command="{Binding SaveOrderCommand}" />

Instead of Click="..." (an event in code-behind) - Command="{Binding ...}" points to a property of type ICommand in the ViewModel. It is ordinary data binding, exactly the same mechanism as with Text="{Binding Name}".

A custom implementation - RelayCommand

WPF has no ready-made class implementing ICommand for general use (it only has specialised ones, e.g. for text editing), so almost every project writes its own, usually called RelayCommand or DelegateCommand:

public class RelayCommand : ICommand
{
    private readonly Action<object> _execute;
    private readonly Predicate<object> _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(parameter);

    public event EventHandler CanExecuteChanged
    {
        // Hooks into the built-in WPF mechanism that polls
        // all commands on every change of focus/UI state
        add => CommandManager.RequerySuggested += value;
        remove => CommandManager.RequerySuggested -= value;
    }
}

Usage in the ViewModel:

public class OrderViewModel : ViewModelBase
{
    private readonly IOrderService _orderService;

    public Order CurrentOrder { get; set; }

    public ICommand SaveOrderCommand { get; }

    public OrderViewModel(IOrderService orderService)
    {
        _orderService = orderService;

        SaveOrderCommand = new RelayCommand(
            execute: _ => SaveOrder(),
            canExecute: _ => CurrentOrder != null && CurrentOrder.Items.Count > 0
        );
    }

    private void SaveOrder()
    {
        _orderService.Save(CurrentOrder);
    }
}

Effect in the UI: as long as CurrentOrder is null or has no items, the Button bound to SaveOrderCommand is automatically greyed out (IsEnabled = false) - without a single line of code in code-behind or XAML responsible for it manually.

CommandManager.RequerySuggested - how this "automagically" works

This is a detail they sometimes ask about, because it looks like magic. CommandManager in WPF listens for typical UI events (clicks, key presses, focus changes) and after each of them automatically calls CanExecute on all registered commands to check whether the IsEnabled state of buttons should change.

The problem with this approach: RequerySuggested reacts only to UI input events - if you change CurrentOrder.Items programmatically (e.g. in code after an API response, without any user interaction), CommandManager doesn't know it should recalculate CanExecute. Then you have to force it manually:

private void AddItem(OrderItem item)
{
    CurrentOrder.Items.Add(item);
    CommandManager.InvalidateRequerySuggested(); // manually tell WPF to recalculate all CanExecute
}

A better version: RelayCommand with explicit control over CanExecuteChanged

Many developers avoid relying on the global CommandManager (because it polls all commands in the application on every click - an overhead in large applications) and instead control it explicitly:

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

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

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

    public event EventHandler CanExecuteChanged;

    // Called manually, exactly when it is KNOWN that something has changed
    public void RaiseCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
private void AddItem(OrderItem item)
{
    CurrentOrder.Items.Add(item);
    ((RelayCommand)SaveOrderCommand).RaiseCanExecuteChanged(); // precyzyjnie, tylko ta komenda
}

This is more efficient, but requires remembering to call it manually everywhere the CanExecute condition changes.

The generic version - a typed parameter

In practice you often want to avoid casting object inside:

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

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

    public bool CanExecute(object parameter) => _canExecute?.Invoke((T)parameter) ?? true;
    public void Execute(object parameter) => _execute((T)parameter);

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

// Usage
public ICommand DeleteOrderCommand => new RelayCommand<Order>(order => _orderService.Delete(order));
<Button Content="Delete" Command="{Binding DeleteOrderCommand}" CommandParameter="{Binding SelectedOrder}" />

CommandParameter in XAML lets you pass any object as an argument to Execute/CanExecute - here, for example, the currently selected order from a ListBox.

Async Command - a common practical problem

ICommand.Execute returns void, so you can't naturally write async Task Execute(...) - you have to work around it:

public class AsyncRelayCommand : ICommand
{
    private readonly Func<Task> _execute;
    private readonly Func<bool> _canExecute;
    private bool _isExecuting;

    public AsyncRelayCommand(Func<Task> execute, Func<bool> canExecute = null)
    {
        _execute = execute;
        _canExecute = canExecute;
    }

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

    public async void Execute(object parameter) // async void - konieczne, bo interfejs wymaga void
    {
        _isExecuting = true;
        RaiseCanExecuteChanged(); // np. wyszarz przycisk na czas trwania operacji

        try
        {
            await _execute();
        }
        finally
        {
            _isExecuting = false;
            RaiseCanExecuteChanged();
        }
    }

    public event EventHandler CanExecuteChanged;
    public void RaiseCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
SaveOrderCommand = new AsyncRelayCommand(
    execute: SaveOrderAsync,
    canExecute: () => CurrentOrder != null
);

private async Task SaveOrderAsync()
{
    await _orderService.SaveAsync(CurrentOrder);
}

async void Execute(...) is the only place where async void is acceptable (instead of async Task) - because the ICommand interface imposes a void signature. This is also a common trick question in interviews: "why do we generally avoid async void, and where is the exception?" - the answer: we avoid it because exceptions from async void can't be caught by a plain try/catch in the caller (they go straight to the SynchronizationContext/crash the app), but ICommand.Execute is one of the few places where we have no choice.

CommunityToolkit.Mvvm - the modern approach (less boilerplate)

Since I mentioned it earlier - most of this code can today be replaced with an attribute:

public partial class OrderViewModel : ObservableObject
{
    [ObservableProperty]
    private Order _currentOrder;

    [RelayCommand(CanExecute = nameof(CanSaveOrder))]
    private async Task SaveOrderAsync()
    {
        await _orderService.SaveAsync(CurrentOrder);
    }

    private bool CanSaveOrder() => CurrentOrder != null && CurrentOrder.Items.Count > 0;
}

The source generator itself creates SaveOrderCommand as an IAsyncRelayCommand, with full CanExecute support and RaiseCanExecuteChanged called automatically when CurrentOrder changes (thanks to [ObservableProperty]).

Summary - why this is better than a plain Click

Click (event) ICommand
Where the logic is Code-behind (breaks MVVM) ViewModel (MVVM-compliant)
Testability Hard (requires the UI) Easy (you call Execute() directly in the test)
Automatic enable/disable You have to do it manually Built in via CanExecute
Reusability The handler is tied to a specific control The same command can be bound from many places (button, menu, keyboard shortcut)

The last point is underrated - a single SaveOrderCommand can be attached at the same time to a button, a menu item and the Ctrl+S keyboard shortcut, without duplicating logic:

<Button Command="{Binding SaveOrderCommand}" Content="Zapisz" />
<MenuItem Command="{Binding SaveOrderCommand}" Header="Zapisz" />
<Window.InputBindings>
    <KeyBinding Command="{Binding SaveOrderCommand}" Key="S" Modifiers="Control" />
</Window.InputBindings>

All three automatically disable/enable together, because they share the same CanExecute.

Buy me a coffee