Model View ViewModel (MVVM) Introduction: Part 2

Model View View-Model is a very powerful design pattern as you know. But if you are a beginner and do not have an idea of MVC MVP then it’s my personal experience that it’s very confusing and painful to understand the logic of MVVM. I am trying to explain the basic fundamentals of MVVM In this series. In this article I‘ll focus fully on the logic and implementation of ICommand.

The following are some core main important components of MVVM:

  • Binding
  • Command
  • Event
  • Converter

I have already provided a MVVM introduction and Data Binding in XAML, if you are beginner then I recommended you go through these articles:

What is Command

Before explaining ICommand in MVVM, you need to know a little bit about the Command Design Pattern because I think ICommand in MVVM comes from the Command Design Pattern. This command pattern is one of the more powerful design patterns in object oriented design patterns. This pattern allows you to decouple the request of an action from the object that actually performs an action, in other words a command pattern represents an action as an object. A Command object does not contain the functionality that is to be executed. This removes the direct link between the command definitions and the functionality and it’s promoting a loose coupling. When you want to implement operations based on the user request then the command pattern is the best pattern to handle your object.

The following are the members of the Command Design Pattern:

  • Client
  • Invoker
  • Command
  • Concrete Command
  • Receiver

Flow of Command Design Pattern



The Invoker is a UI element. The Receiver is nothing but a handling method, it can be some code implementation or some business logic that will be executed whenever a command is to be executed. Between some layers is this nothing just interface layers. Because an invoker (XAML Element event binding) depends only on the interface based. This is the core logic of a command between many things that are reelvant as the client or some concrete method, I am not covering all points because my target is ICommand MVVM. If you want to learn the Command Design Pattern then you can learn here with a nice explanation.

What is ICommand

An ICommand is a core component of MVVM. ICommand is frequently used in MVVM, it provides separation logic between a View and View Model (User Interface and Business Logic). XAML offers a way to bind your GUI event better by ICommand. ICommand requires the user to define two methods, bool CanExecute and void Execute. The CanExecute method really just says to the user, can I execute this Action? This is useful for controlling the context in which you can perform GUI actions.

ICommand is very simple but it’s more interesting and complicated when you are using it in an application. ICommand integrates your User Interface to business logic or it’s making a direct communication between a View to a View Model. It also provides a mechanism for the view to update the model/view-model. All mechanisms and scenarios are similar and simple, but an implementation seems different and it can be confusing. So I will explain step-by-step how to use and implement ICommand in your application.



The ICommand interface provides very useful methods and events, like the Execute() and CanExecute() methods and the CanExecuteChanged Event. The preceding Snap ICommand interface specifies and ICommand members.

  • Execute (object): This method is called when a Command is triggered. It has only one object parameter, the Execute (object). Which can be used to additional information and it has a void return type.
  • CanExecute (object): It also has only one object parameter but it’s returning a bool value, if it’s returning true then it means the command can execute. If you have used XAML controls that support the Command property then the control will be automatically disabled. I‘ll explain in a sample application what hapens when it returns false.
  • CanExecuteChanged: This is event mast be raised by the command implementation when the CanExecute method needs to be reevaluated or else after the user has filled in a field. The CanExecuteChanged event exists so we can check if the Save button should be enabled.

Before implementing a core implementation and use ICommand we should understand how the Internal interface works. For that, I am explaining below the command line and am creating one small Hello World sample with the use of my own ICommand Interface.

using System;

using System.Diagnostics;

using System.Text;

 

namespace CommandPattern

{

 

    public interface ICommand

    {

        void Execute(object parameter);

        bool CanExecute(object parameter);

        event EventHandler CanExecuteChanged;

    }

 

    public class HelloCommandPattern : ICommand

    {

        public void Execute(object parameter)

        {

            Debug.WriteLine(parameter);

        }

        public bool CanExecute(object parameter)

        {

            return parameter != null;

        }

        public event EventHandler CanExecuteChanged;

        static void Main(string[] arg)

        {

            var parm = new HelloCommandPattern();

            if (!parm.CanExecute(null))

                parm.Execute("Hello World");

        }

    }

}

public ICommand Command;

public void ToVM()

{

   Command = new HelloCommandPattern();

   if (!Command.CanExecute(this))

   Command.Execute(this);

}


In the preceding I create one sample console application with an ICommand Interface the same as the System.Windows.Input interface. CanExecute() andExecute() are two methods and one event handler is CanExecuteChanged. The main object of this console app is to clarify our ICommand logic.

And attempt to explain how the CanExecute() and Execute() methods work in MVVM. I am ing a value to a console prompt and the first validation here is if it is executable, if true is returned then finally executing my statement.

ICommand behaves similarly but here the or parameter is fixed so we are able to it easily. In MVVM ICommand we use a delegate and an Action, func is some delegate.

One WPF MVVM ICommand Example

ViewModel

using System.Windows.Input;

using System.Windows;

namespace HelloMVVM

{

    class MainViewModel

    {

        private ICommand buttonCommand;

        public ICommand ClickCommand

        {

            get

            {

                return buttonCommand;

            }

            set

            {

                buttonCommand = value;

            }

        }

        public MainViewModel()

        {

            ClickCommand = new RelayCommand(new Action<object>(Message));

        }

        public void Message(object obj)

        {

            MessageBox.Show(obj.ToString());

        }

    }

}

In the preceding I create one view model, it’s nothing but one simple C# class, here I am calling an ICommand interface and creating one ICommand Property and one method exists in which I am ing a simple message. In the constructor I am ing my Message() by the RelayCommand. And assigning a value to ClickCommand, its Icommand property that I’ll bind to the XAML element. Here I am using RelayCommand; it’s just an implementation of an ICommand Member and an Action and Delegate implementation.

RelayCommand
 

using System.Collections.Generic;

using System.Text;

using System.Windows.Input;

namespace HelloMVVM

{

    class RelayCommand : ICommand

    {

        private Action<object> _action;

        public RelayCommand(Action<object> action)

        {

            _action = action;

        }

        #region ICommand Members

        public bool CanExecute(object parameter)

        {

            return true;

        }

        public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)

        {

            if (parameter != null)

            {

                _action(parameter);

            }

            else

            {

                _action("msg");

            }

        }

        #endregion

    }

}

ViewModel to View Binding in MVVM



In the preceding images I show how Icommand binds to a View and how to call RelayCommand in a View-model. The following describes that procedure:

  1. Create view Model
  2. Create Method
  3. Relay the command class that was added, inside the relay command I am using an action delegate and ing a method as a parm. What is Action in C#? is a nice explanation of the Action Delegate.
  4. Bind the View Model to the View or assign a data context.
  5. Bind the ICommand.
Response processing when user clicks a button


As before in the article earlier, the data bound between the UI and ViewModel is explained in the following if you are a beginner:

Data Binding in XAML

In the preceding image I tried to explain my MVVM sample application operation and ICommand binding flow in a very simple way.
  1. A user presses a button on the screen (performs an action).
  2. A corresponding event is fired to the binder.
  3. The binder finds the corresponding action logic (it is Command) in the ViewModel and executes it.
  4. The action logic accesses data from the Model layer and updates the View Model’s corresponding properties.
  5. Binder then updates the corresponding UI components to provide visual feedback to the user.