ICommand Interface In MVVM - WPF

In this article, we will learn about button click event in WPF with MVVM concept. We use ICommand interface for generating the button click event. Let's take one simple example of one simple textbox and button.  After writing the text in textbox, when we click on button, it will display a simple message box.

Before staring this article, please read Explain INotifyPropertyChanged In WPF - MVVM article first.

First, create one WPF application and create a window like the following.

Run the application

XAML code 
  1. <Window x:Class="MVVM_ICommand.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525">  
  2.     <StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center">  
  3.         <TextBox Width="120" Height="30" Margin="10"></TextBox>  
  4.         <Button Width="90" Margin="10" Content="Click Me"></Button>  
  5.     </StackPanel>  
  6. </Window>  
Now, we have to create one command class along with a View-Model class. View-Model contains some properties like Name. Now, let's implement the View-Model with INotifyProperyChanged interface. This implementation is given in my previous article.

Give View-Model namespace reference to the View and define the window resource file. Then, give data context to the parent control and also, bind the text property of the text box. 

Now, let’s start our main code for making a new class RelayCommand. Make it as public.
  1. public class RelayCommand {}  
  2.   
  3. Now implement the interface ICommand  
  4. public class RelayCommand: ICommand {  
  5.     public boolCanExecute(object parameter) {  
  6.   
  7.     }  
  8.     public event EventHandlerCanExecuteChanged;  
  9.     public void Execute(object parameter) {  
  10.   
  11.     }  
  12. }  
It will create two methods and one event. The first method "CanExecute" decides whether we are allowed to fire the command ( the button click event) or not. The second method "Execute" method contains the actual logic. If CanExecute method returns true, then Execute method is run.

Now, Create two action properties that we initialize in constructor of the relay command class.
  1. Action < object > _execteMethod;  
  2. Func < bool, object > _canexecuteMethod;  
  3.   
  4. public RelayCommand(Action < object > execteMethod, Func < bool, object > canexecuteMethod) {  
  5.     _execteMethod = execteMethod;  
  6.     _canexecuteMethod = canexecuteMethod;  
  7. }  
Here, in CanExecute method, we put null validation to check if _canexecutemethod is initialized or not. If not, then it returns false; otherwise it returns true. Also, write the logic for Execute method. Here, we simply initialize the _execute method because we make this RelayCommand class to be generalized.
  1. public boolCanExecute(object parameter) {  
  2.     if (_canexecuteMethod != null) {  
  3.         return true;  
  4.     } else {  
  5.         return false;  
  6.     }  
  7. }  
  8.   
  9.   
  10. public void Execute(object parameter) {  
  11.     _execteMethod(parameter);  
  12. }  
Now, let's define “CanExecuteChanged” the event logic, which will run the canExecute method continuously.
  1. public event EventHandlerCanExecuteChanged  
  2. {  
  3. add { CommandManager.RequerySuggested += value; }  
  4. remove { CommandManager.RequerySuggested -value; }  
  5. }  
Full RelayCommand class code
  1. public class RelayCommand: ICommand  
  2. Action < object > _execteMethod;  
  3. Func < bool, object > _canexecuteMethod;  
  4.   
  5. public RelayCommand(Action < object > execteMethod, Func < bool, object > canexecuteMethod) {  
  6.     _execteMethod = execteMethod;  
  7.     _canexecuteMethod = canexecuteMethod;  
  8. }  
  9.   
  10. public boolCanExecute(object parameter) {  
  11.     if (_canexecuteMethod != null) {  
  12.         return _canexecutemethod(parameter);  
  13.     } else {  
  14.         return false;  
  15.     }  
  16. }  
  17.   
  18. public event EventHandlerCanExecuteChanged {  
  19.     add {  
  20.         CommandManager.RequerySuggested += value;  
  21.     }  
  22.     remove {  
  23.         CommandManager.RequerySuggested -value;  
  24.     }  
  25. }  
  26.   
  27. public void Execute(object parameter) {  
  28.     _execteMethod(parameter);  
  29. }  
  30. }  
Now, go for the View-Model class and create the ICommand property, as shown below.

public ICommandMyCommand { get; set; }

And, also create two methods like,
  1. private boolCanExecuteMyMethod(object parameter) {  
  2.     if (string.IsNullOrEmpty(Name)) {  
  3.         return false;  
  4.     } else {  
  5.         if (Name < > "") {  
  6.             return true;  
  7.         } else {  
  8.             return false;  
  9.         }  
  10.   
  11.     }  
  12. }  
  13.   
  14. private void ExecuteMyMethod(object parameter) {  
  15.     MessageBox.Show("Hello... " + Name);  
  16. }  
Now, create constructor for View-Model and pass both these methods to it.
  1. public ViewModel()  
  2. {  
  3. MyCommand = new RelayCommand(ExecuteMyMethod, CanExecuteMyMethod);  
  4. }  
Full View-Model Code
  1. public class ViewModel {  
  2.   
  3.     public ICommandMyCommand {  
  4.         get;  
  5.         set;  
  6.     }  
  7.   
  8.     private string _name;  
  9.   
  10.     public string Name {  
  11.         get {  
  12.             return _name;  
  13.         }  
  14.         set {  
  15.             _name = value;  
  16.         }  
  17.     }  
  18.   
  19.     public ViewModel() {  
  20.         MyCommand = new RelayCommand(ExecuteMyMethod, CanExecuteMyMethod);  
  21.     }  
  22.   
  23.   
  24.     private boolCanExecuteMyMethod(object parameter) {  
  25.         if (string.IsNullOrEmpty(Name)) {  
  26.             return false;  
  27.         } else {  
  28.             if (Name < > "") {  
  29.                 return true;  
  30.             } else {  
  31.                 return false;  
  32.             }  
  33.   
  34.         }  
  35.     }  
  36.   
  37.     private void ExecuteMyMethod(object parameter) {  
  38.         MessageBox.Show("Hello... " + Name);  
  39.     }  
  40.   
  41. }  
Now, go for the design View. Build the Solution and open the View's XAML code. Set the command property and give command a name.

<Button Width="90" Margin="10" Content="Click Me" Command="{Binding MyCommand}"></Button>

Full XAML Code
  1. <Window x:Class="MVVM_ICommand.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:viewmodel="clr-namespace:MVVM_ICommand.ViewModel" Title="MainWindow" Height="350" Width="525">  
  2.     <Window.Resources>  
  3.         <viewmodel:ViewModel x:Key="vm"></viewmodel:ViewModel>  
  4.     </Window.Resources>  
  5.     <StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center" DataContext="{Binding Source={StaticResourcevm}}">  
  6.         <TextBox Width="120" Height="30" Margin="10" Text="{Binding Path=Name , Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></TextBox>  
  7.         <Button Width="90" Margin="10" Content="Click Me" Command="{Binding MyCommand}"></Button>  
  8.     </StackPanel>  
  9. </Window>  
Run the application.
Write the text in text box and click on button.
 This will display a message, as shown below.
Run the application
 
This is how this command interface works in MVVM . If you have any confusion, you can download the attached source code and debug it line by line.