ICommand MVVM implementation
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
In MVVM, ICommand lets the view trigger ViewModel logic without code-behind event handlers. The usual implementation is a reusable command class, often called RelayCommand, that wraps an execute action and an optional CanExecute rule.
Why ICommand Exists In MVVM
The point of MVVM is to keep UI behavior testable and separate from the view. Instead of writing a click handler in the window code-behind, you expose a command from the ViewModel and bind the button to it.
The ICommand interface has three parts:
- '
Execute' - '
CanExecute' - '
CanExecuteChanged'
That is enough to model most button, menu, and toolbar actions in WPF.
A Simple RelayCommand Implementation
Here is a straightforward implementation:
This implementation works well for commands that do not need a parameter. CommandManager.RequerySuggested is convenient in WPF because it prompts the UI to reevaluate whether buttons should be enabled.
Use The Command In A ViewModel
Now expose a command from the ViewModel:
Here the command stays disabled until Name contains non-whitespace text. That is the main value of CanExecute: the UI updates its enabled state automatically from ViewModel logic.
Bind It In XAML
The view binding stays simple:
The button does not know anything about the save logic. It only knows it should invoke the bound command.
That keeps the view declarative and the behavior testable.
Support Command Parameters When Needed
Many MVVM projects also define a generic version so commands can receive a typed parameter.
That is useful for list actions, selected-item commands, and context menu operations.
Common Pitfalls
The biggest mistake is putting UI logic back into code-behind and only using ICommand superficially. If the behavior matters to the view state, it usually belongs in the ViewModel.
Another common issue is forgetting to refresh CanExecute. If the underlying state changes and the UI does not requery the command, buttons can stay stuck enabled or disabled.
People also overcomplicate command classes. A small reusable RelayCommand is enough for many applications. You do not need a custom command type for every button.
Finally, be careful with async work. An async void command body can hide exceptions and reentrancy problems. For long-running tasks, use an async-aware command pattern rather than pretending every action is instant.
Summary
- '
ICommandis the MVVM bridge between the view and ViewModel actions.' - A
RelayCommandwraps execute logic and optional enablement rules. - '
CanExecutecontrols whether the bound UI element is enabled.' - XAML binds directly to commands, keeping the view free of event-handler logic.
- For parameters or async workflows, extend the basic pattern deliberately instead of bypassing it.

