All Resources
Code Snippet.NET2026-03-08
WPF RelayCommand Pattern
A clean implementation of the ICommand interface for WPF MVVM applications. Supports both synchronous and async execution with CanExecute logic.
csharp
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 event EventHandler? CanExecuteChanged
{
add => CommandManager.RequerySuggested += value;
remove => CommandManager.RequerySuggested -= value;
}
public bool CanExecute(object? param) =>
_canExecute?.Invoke(param) ?? true;
public void Execute(object? param) => _execute(param);
}How It Works
RelayCommand is the foundation of the MVVM command pattern in WPF. It wraps any action into an ICommand that can be bound directly to buttons, menu items, and other UI controls.
- Constructor takes an execute action and an optional canExecute predicate
- CanExecuteChanged hooks into CommandManager.RequerySuggested so WPF automatically re-evaluates button enabled states
- Execute simply invokes the stored action with the command parameter
Usage Example
In your ViewModel:
public ICommand SaveCommand => new RelayCommand(
_ => Save(),
_ => CanSave);In your XAML:
<Button Content="Save" Command="{Binding SaveCommand}" />Tips
- For async commands, create an AsyncRelayCommand variant that wraps Func<Task> instead of Action
- The CommunityToolkit.Mvvm NuGet package provides production-grade RelayCommand and AsyncRelayCommand implementations
- Call CommandManager.InvalidateRequerySuggested() to force WPF to re-check all CanExecute states
WPFMVVMC#.NET