ICommand Interface and RelayCommand Class in WPF MVVM


ICommand Interface and RelayCommand Class in WPF MVVM

ICommand Interface and RelayCommand Class in WPF are commonly used for binding. ICommand Interface and RelayCommand class is implemented in the ViewModel and is exposed to the view controls.

Every view in the app has an empty codebehind file, except for the standard code that calls InitializeComponent in the class's constructor. In fact, you could remove the views' codebehind files from the project and the application would still compile and run correctly. Despite the lack of event handling methods in the views, when the user clicks on buttons, the application reacts and satisfies the user's requests. This works because of bindings that were established on the Command property of Hyperlink, Button, and MenuItem controls displayed in the UI. Those bindings ensure that when the user clicks on the controls, ICommand objects exposed by the ViewModel execute. You can think of the command object as an adapter that makes it easy to consume a ViewModel's functionality from a view declared in XAML.

When a ViewModel exposes an instance property of type ICommand, the command object typically uses that ViewModel object to get its job done.

We will try to understand ICommand Interface and RelayCommand Class with following example.

Create a View and ViewModel like following:

View: Lets create the view first.  Three things to note in this view

1. In this view, I have included MyWPFSample namespace

xmlns:local="clr-namespace:MyWPFSample"

2. I have set datacontext of the winodw to the MainWindowViewModel class present in MyWPFSample namespace


   
   

3. I have done binding of the command of the button with the ButtonCommand property of MainWindowViewModel class.

Command="{Binding ButtonCommand}"


        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:MyWPFSample"
        Title="MainWindow" Height="150" Width="370">