Different approaches for Commands/Command Logic while implementing Prism & MVVM in WPF

MVVM enforces empty code behind files, except the standard code that calls InitializeComponent inside the constructor. Even if you remove code behind file from the project still it will compile and run correctly.
Even without having event handler in the code behind application can be made to react on the user interaction events. It can be done by binding ICommand object exposed by ViewModel layer with UI controls. Command is an object that makes it easy to consume ViewModel’s functionality from the view declared in XAML.

Usually ViewModel has to expose a property of type ICommand. This command property is usually initialized in the constructor of ViewModel.

For example –  Following code has been taken from one of my previous blog post on Navigation in Prism with MVVM.


  public class NavigatorViewModel
    {
        IEventAggregator eventAggregator;
        ICommand navigateToRevenueCommand;
        ICommand navigateToSalesCommand;
        string activeWorkspace;

        public NavigatorViewModel(IEventAggregator eventAggregator)
        {
            this.eventAggregator = eventAggregator;
            this.activeWorkspace = "Revenue";
            this.navigateToRevenueCommand = new NavigateToRevenueCommand(this);
            this.navigateToSalesCommand = new NavigateToSalesCommand(this);
        }

       public ICommand NavigateToRevenue
       {
           get
           {
               return navigateToRevenueCommand;
           }
           set
           {
               navigateToRevenueCommand = value;
           }
       }

       public ICommand NavigateToSales
       {
           get
           {
               return navigateToSalesCommand;
           }
           set
           {
               navigateToSalesCommand = value;
           }
       }

       public string ActiveWorkspace
       {
           get
           {
               return activeWorkspace;
           }
           set
           {
               activeWorkspace = value;
           }
       }

       public IEventAggregator EventAggregator
       {
           get
           {
               return eventAggregator;
           }
           set
           {
               eventAggregator = value;
           }
       }


    }


This class exposes ICommand property which has been instantiated inside the constructor of the class.
Even it can be injected or can have private class to implement the ICommand Interface. But it becomes difficult if you have too many commands in your ViewModel class.


Microsoft Composite Application Library introduces DelegateCommand which can be used for command implementation within the module.

Recently I have designed a class to simplify the Command implementation by generalizing it I have created SaralCommand as part of Saral Framework hosted on Codeplex.com
I will describe it in my next blog post.

No comments: