Basics of WPF ICommand Interface in MVVM

Basics of WPF ICommand Interface in MVVM

I am going to cover basics of ICommand interface in WPF in MVVM pattern like syntax of ICommand interface, methods and events of ICommand interface, how to bind ICommand in View(XAML), how to implement ICommand interface in ViewModel etc. 

1. Namespace for ICommand

System.Windows.Input
Assembly: System

System.Windows.Input supports many Classes, Structures, Interfaces, Delegates and Enumerations. Here is the complete list on MSDN.

2. Methods exposed by ICommand

A) CanExecute: Defines the method that determines whether the command can execute in its current state. Typically, a command source calls the CanExecute method when the CanExecuteChanged event is raised.

Syntax: bool CanExecute(Object parameter)

Parameter: System.Object
Return Value: Boolean

B) Execute: Defines the method to be called when the command is invoked.

Syntax: void Execute(Object parameter)

Parameter: System.Object

3. Events exposed by ICommand

A) CanExecuteChanged: Occurs when changes occur that affect whether or not the command should execute.

Syntax: event EventHandler CanExecuteChanged

Implement the command by defining a class that implements ICommand and specifically implement the Execute method.

A complete ICommand Interface looks like:

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

How to use ICommand in View (XAML)?

I am creating a Save button and binding ICommand to it.


CommandParameter: A parameter can be passed through the "CommandParameter" property. The CommandParameter is sent to both CanExecute and Execute events.

Further readings: