ICommand Interface in WPF is commonly used for binding. ICommand Interface is implemented in the ViewModel and are exposed to the view controls.
Introduction
This article explains about Icommand usage in MVVM pattern with WPF
The ICommand interface is defined inside the System.Windows.Input namespace. It has two methods and an event.
Methods
CanExecute:- Defines the method that determines whether the command can execute in its current state.
Execute :- Defines the method to be called when the command is invoked.
Events
CanExecuteChanged:-Occurs when changes occur that affect whether or not the command should execute.
let us try to understand ICommand Interface and RelayCommand Class with following example
Create a view and viewModel
View: Lets create the view first. Three things to note in this view
1. In this view, WpfApplication1 namespace is included
xmlns:local="clr-namespace:WpfApplication1"
2. Datacontext of the window is set to the MainWindowViewModel class present in WpfApplication1 namespace
<Window.DataContext>
<local:MainWindowViewModel/>
</Window.DataContext>
3. Binding of the command of button is done with the updateCommand property of MainWindowViewModel class.
<Button Content="Update" Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="310,40,0,0" Name="btnUpdate"
VerticalAlignment="Top" Width="141"
Command="{Binding Path=UpdateCommad}" />
ViewModel: ViewModel has namespace WpfApplication1 , and property as updateCommand.
private ICommand mUpdater;
public ICommand UpdateCommand
{
get
{
if (mUpdater == null)
mUpdater = new Updater();
return mUpdater;
}
set
{
mUpdater = value;
}
}
private class Updater : ICommand
{
#region ICommand Members
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
}
#endregion
}
}
}
When the user clicks on update Button, the application reacts and satisfies the user's requests. This works because of bindings that were established on the Command property of Button displayed in the UI. The command object acts as an adapter that makes it easy to consume a ViewModel's functionality from a view declared in XAML