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.

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.

public class RelayCommand {}

Now implement the interface ICommand

public class RelayCommand: ICommand {

public boolCanExecute(object parameter) {

}

public event EventHandlerCanExecuteChanged;

public void Execute(object parameter) {

}

}

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.

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.

public boolCanExecute(object parameter) {

if (_canexecuteMethod != null) {

return true;

} else {

return false;

}

}

public void Execute(object parameter) {

_execteMethod(parameter);

}

Now, let's define “CanExecuteChanged” the event logic, which will run the canExecute method continuously.