Commands in WPF and Silverlight : Detailed Explanation

In WPF and Silverlight world, Commands provide a convenient way to represent actions or operations that can be easily bound to controls in the UI. They encapsulate the actual code that implements the action or operation and help to keep it decoupled from its actual visual representation in the view. The Commands have basically two purposes:

a)      To separate the semantics and the object that invokes a command from the logic that executes the command.

b)      To indicate whether an action is actually available at the time of its invoking.

Any Command can be represented and invoked using many different ways: Mouse clicks, shortcut key presses, touch gestures, or any other input events. Interaction between the UI controls in the view and the command can be two-way. The command can be invoked as the user interacts with the UI, and the UI can be automatically enabled or disabled as the underlying command becomes enabled or disabled.

Commands are based on the Command design pattern. Typically, with commands you have an invoker and a receiver and some infrastructure in between to keep those two parties decoupled from one another as much as possible. The invoker is typically a UI element of some sort like a button, menu, or possibly a combo box selection. The receiver is the handling code that takes some action based on the command being invoked.

The command pattern is a behavioral design pattern in which an object is used to represent and encapsulate all the information needed to call a method at a later time. This information includes the method name, the object that owns the method and values for the method parameters. This object is typically a Command object.

Four terms always associated with the command pattern are command, receiver, invoker and client. A command object has a receiver object and invokes a method of the receiver in a way that is specific to that receiver’s class. The receiver then does the work. A command object is separately passed to an invoker object, which invokes the command, and optionally does bookkeeping about the command execution. Any command object can be passed to the same invoker object. Both an invoker object and several command objects are held by a client object. The client contains the decision making about which commands to execute at which points. To execute a command, it passes the command object to the invoker object. If you want to dig deeper into the Command Design pattern, look at this nice explanation: http://www.dofactory.com/Patterns/PatternCommand.aspx#_self1

class Client
{
static void Main(string[] args)
{
Invoker i = new Invoker();
//save undo to position 100
ICommand a = new UndoCommand(100);
i.AddCommand(a);
//save undo to position 200
ICommand b = new UndoCommand(200);
i.AddCommand(b);
//perform the undo
i.RunCommand(); //the client does not need to know about the details of the undo
}
}

public interface ICommand
{
void Execute();
}


public class UndoCommand : ICommand
{
private int location;
public int Location
{
get { return location; }
}
public UndoCommand(int originalLocation)
{
location = originalLocation;
}
public void Execute()
{
new UndoPerformer().Undo(this);
}
}

public class Invoker
{
private Stack commandList = new Stack();
public void RunCommand()
{
while (commandList.Count > 0)
commandList.Pop().Execute();
}
public void AddCommand(ICommand c)
{
commandList.Push(c);
}
}

public class UndoPerformer
{
public void Undo(ICommand c)
{
if (c is UndoCommand)
{
int originalLocation = (c as UndoCommand).Location;
Console.WriteLine("Moving back to position: " + originalLocation);
}
}
}

DelegateCommand and CompositeCommand

In the following section, we will be focusing specifically on DelegateCommand and CompositeCommand. These are the two implementations defined by Prism framework and both implements the ICommand interface. Both are implementations of the ICommand interface defined in WPF and Silverlight, which defines three members: an Execute method, a CanExecute method, and a CanExecuteChanged event. The Execute method is the crux of the ICommand interface, it is what will be invoked whenever the invoker element has the triggering action happen to it (i.e. a button is clicked that has a command hooked up to it). The CanExecute method can be optionally hooked up to conditionally say whether the associated invoker should be enabled or not – for example if a document is not dirty, the Save command should be disabled. The associated CanExecuteChanged event is a way for the supporting logic that determines whether the command should be enabled to notify the invoker that it should re-evaluate the CanExecute state of the command and update the UI appropriately as things are changing behind the scenes (i.e. the document just went dirty because the user input some text or some other formatting command was invoked on the document that the Save command relates to).

There are two ways in which any Commands can be implemented in View Models: Either as CommandMethod or as a CommandObject. In either case, the view’s interaction with the command can be defined declaratively without requiring complex event handling code in the view’s code-behind file. Most of the WPF and Silverlight Controls inherently support commands and provide a Command property that can be data bound to an ICommand object provided by the view model. In other cases, a command behavior can be used to associate a control with a command method or command object provided by the view model.
Let’s take a deeper look into either of the two ways of implementing Commands in the View Models:

Implementing DelegateCommand as CommandObject

DelegateCommand class encapsulates two delegates that each reference a method implemented within your view model class. It inherits from the DelegateCommandBase class, which implements the ICommand interface’s Execute and CanExecute methods by invoking these delegates. You specify the delegates to your view model methods in the DelegateCommand class constructor, which is defined as follows:

public class DelegateCommand : DelegateCommandBase
{
public DelegateCommand(Action executeMethod,Func<T,bool> canExecuteMethod ): base((o) => executeMethod((T)o), (o) => canExecuteMethod((T)o))
{
...
}
}

The following code example shows how a DelegateCommand instance, which represents a Submit command, is constructed by specifying delegates to the OnSubmit and CanSubmit view model methods.

public class ViewModel
{
public ViewModel()
{
this.SubmitCommand = new DelegateCommand<object>(
this.OnSubmit, this.CanSubmit );
}
public ICommand SubmitCommand { get; private set; }
private void OnSubmit(object arg)   {...}
private bool CanSubmit(object arg)  { return true; }
}

Invoking Command Objects from the View
There are a number of ways in which a control in the view can be associated with a command object proffered by the view model. Certain WPF and Silverlight 4 controls, notably ButtonBase derived controls, such as Button or RadioButton, and Hyperlink, or MenuItem derived controls, can be easily data bound to a command object through the Command property. WPF also supports binding view model ICommand to a KeyGesture.

Button Command="{Binding Path=SubmitCommand}" CommandParameter="SubmitOrder"

A command parameter can also be optionally defined using the CommandParameter property. The type of the expected argument is specified in the Execute and CanExecute target methods. The control will automatically invoke the target command when the user interacts with that control, and the command parameter, if provided, will be passed as the argument to the command’s Execute method. In the preceding example, the button will automatically invoke the SubmitCommand when it is clicked. Additionally, if a CanExecute handler is specified, the button will be automatically disabled if CanExecute returns false, and it will be enabled if it returns true.

An alternative approach is to use Expression Blend interaction triggers and InvokeCommandAction behavior.

<Button Content="Submit" IsEnabled="{Binding CanSubmit}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<i:InvokeCommandAction Command="{Binding SubmitCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>

This approach can be used for any control to which you can attach an interaction trigger. It is especially useful if you want to attach a command to a control that does not derive from ButtonBase, or when you want to invoke the command on an event other than the click event. Again, if you need to supply parameters for your command, you can use the CommandParameter property.
Unlike controls that can be bound directly to a command, InvokeCommandAction does not automatically enable or disable the control based on the command’s CanExecute value. To implement this behavior, you have to data bind the IsEnabled property of the control directly to a suitable property on the view model, as shown earlier.

Invoking Command Methods from the View
An alternative approach to implementing commands as ICommand objects is to implement them simply as methods in the view model and then to use behaviors to invoke those methods directly from the view.
This can be achieved in a similar way to the invocation of commands from behaviors, as shown in the previous section. However, instead of using InvokeCommandAction, you use the CallMethodAction. The following code example calls the (parameter-less) Submit method on the underlying view model.

<Button Content="Submit" IsEnabled="{Binding CanSubmit}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<i:CallMethodAction TargetObject="{Binding}" Method="Submit"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>

The TargetObject is bound to the underlying data context (which is the view model) by using the {Binding} expression. The Method parameter specifies the method to invoke.

Composite Commands

In many cases, a command defined by a view model will be bound to controls in the associated view so that the user can directly invoke the command from within the view. However, in some cases, you may want to be able to invoke commands on one or more view models from a control in a parent view in the application’s UI.

For example, if your application allows the user to edit multiple items at the same time, you may want to allow the user to save all the items using a single command represented by a button in the application’s toolbar or ribbon. In this case, the Save All command will invoke each of the Save commands implemented by the view model instance for each item. This is where the CompositeCommand comes in.

The CompositeCommand class represents a command that is composed from multiple child commands. When the composite command is invoked, each of its child commands is invoked in turn. It is useful in situations where you need to represent a group of commands as a single command in the UI or where you want to invoke multiple commands to implement a logical command.

Similar to the DelegateCommand, the C0mpositeCommand implements the ICommand interface. The CompositeCommand class maintains a list of child commands (DelegateCommand instances). The Execute method of the CompositeCommand class simply calls the Execute method on each of the child commands in turn. The CanExecute method similarly calls the CanExecute method of each child command, but if any of the child commands cannot be executed, the CanExecute method will return false. In other words, by default, a CompositeCommand can only be executed when all the child commands can be executed.

Apart from the Execute and CanExecute methods, there are two more methods that are worth looking into. They are RegisterCommand and UnRegisterCommand.

Registering and Unregistering Child Commands with the Composite Commands

Child commands are registered or unregistered using the RegisterCommand and UnregisterCommand methods.

commandProxy.SubmitAllOrdersCommand.RegisterCommand(
orderCompositeViewModel.SubmitCommand );
commandProxy.CancelAllOrdersCommand.RegisterCommand(
orderCompositeViewModel.CancelCommand )

Composite commands at the parent view level will often be used to coordinate how commands at the child view level are invoked. In some cases, you will want the commands for all shown views to be executed, as in the Save All command. In other cases, you will want the command to be executed only on the active view. In this case, the composite command will execute the child commands only on views that are deemed to be active; it will not execute the child commands on views that are not active. To support this scenario, Prism provides the IActiveAware interface. The IActiveAware interface defines an IsActive property that returns true when the implementer is active, and an IsActiveChanged event that is raised whenever the active state is changed.

You can implement the IActiveAware interface on child views or view models. It is primarily used to track the active state of a child view within a region. Whether or not a view is active is determined by the region adapter that coordinates the views within the specific region control.

The DelegateCommand class also implements the IActiveAware interface. The CompositeCommand can be configured to evaluate the active status of child DelegateCommands (in addition to the CanExecute status) by specifying true for the monitorCommandActivity parameter in the constructor. When this parameter is set to true, the CompositeCommand class will consider each child DelegateCommand’s active status when determining the return value for the CanExecute method and when executing child commands within the Execute method.

When the monitorCommandActivity parameter is true, the CompositeCommand class exhibits the following behavior:

CanExecute. Returns true only when all active commands can be executed. Child commands that are inactive will not be considered at all.
Execute. Executes all active commands. Child commands that are inactive will not be considered at all.

By implementing the IActiveAware interface on your child view models, you will be notified when your child view becomes active or inactive with the region. When the child view’s active status changes, you can update the active status of the child commands.

Differences : CompositeCommand and DelegateCommand

There are several differences about the CompositeCommand implementation and the DelegateCommand implementation. The first is that the CompositeCommand is an aggregation of other commands – a list of ICommand references internally. It allows you to hook up multiple command targets to a single root command that itself can be hooked up to a command source such as a button or menu item. Figure 1 shows this relationship. The CompositeCommand can hold references to any ICommand object, but typically you will use it in conjunction with DelegateCommands. When the CompositeCommand.Execute method is invoked, it will invoke the Execute method on each of the child commands. When CompositeCommand.CanExecute is called to determine whether the command is enabled, it polls its child commands for their result from CanExecute.Child commands register themselves with the composite command and can also unregister if appropriate. In this way, it is very similar to a subscribe/unsubscribe of an event, but with the additional functionality of commands to enable and disable the commands based on custom logic.

Another thing different about CompositeCommands is that they can be hooked up to a source control ahead of time, before any child commands have registered. DelegateCommands have to be pointed to their target methods through a delegate at the point where they are constructed. As a result, CompositeCommands allow an extra layer of separation between the source (i.e. toolbar button or menu item) and the target (handling method) – decoupled in lifetime. Because they can target multiple child commands, they also work well for distributed logic such as a Save All command that needs to be dispatched to multiple open documents, each of which has their own handling logic in their view model.

MVVM UnPlugged

In Part 1 of the MVVM series “MVVM Unplugged – Definition, Benefits, Classes and its interactions“, we saw that the MVVM pattern provides a clean separation between your application’s user interface, its presentation logic, and its business logic and data by separating each into separate classes. In this blog, we are going to focus on the Data Binding aspect of implementing the MVVM pattern esp. Databinding of properties using INotifyPropertyChanged interface.

Data Binding

Data binding is one of the very important mechanism through which the various classes under the MVVM pattern interact with each other.WPF and Silverlight both provide powerful data binding capabilities. Silverlight and WPF data binding supports multiple data binding modes. There are various modes of data binding, with one-way data binding, UI controls can be bound to a view model so that they reflect the value of the underlying data when the display is rendered. Two-way data binding will also automatically update the underlying data when the user modifies it in the UI. To achieve data binding and to make ensure that the UI is kept up to date when the data changes in the view model, it should implement the appropriate change notification interfaces.  If there are properties in the ViewModel that needs to be data bound with the view then the view model should implement the INotifyPropertyChanged interface. If the view model represents a collection, it should implement the INotifyCollectionChanged interface or derive from the ObservableCollection class that provides an implementation of this interface. The INotifyPropertyChanged interface and INotifyCollectionChanged interface both define an event that is raised whenever the underlying data is changed. Any data bound controls will be automatically updated when these events are raised. WPF and Silverlight data binding supports binding to nested properties via the Path property. Thumb rule for achieving data binding in WPF or Silverlight is that any view model or model that is accessible to the view should implement either the INotifyPropertyChanged or INotifyCollectionChanged interfaces, as per the need.

In this blog, we are going to focus on the implementation of the INotifyPropertyChanged interface. If we look in the object browser of the INotifyPropertyChanged, we see that it’s a very simple interface and it is just asking the concrete classes to expose an event which takes in a delegate PropertyChangedEventHandler delegate.

namespace System.ComponentModel
{
       // Summary: Notifies clients that a property value has changed.
       public interface INotifyPropertyChanged
       {
           // Summary: Occurs when a property value changes.
           event PropertyChangedEventHandler PropertyChanged;
       }
}

The PropertyChangedEventHandler is defined as a method that will handle the INotifyPropertyChanged. PropertyChanged event is raised when a property is changed on a component. It takes in two parameters:

  •  sender – The source of the event.
  •  e – A System.ComponentModel.PropertyChangedEventArgs that contains the event data.

If we look into the PropertyChangedEventArgs, it has a constructor which takes in a parameter PropertyName as string now this parameter is basically is the property which has changed.

public PropertyChangedEventArgs(string propertyName);

Now since we have a basic understanding of how the INotifyPropertyChanged interface works and what constitutes the PropertyChangedEventHandler and PropertyChangedEventArgs. Lets take a look at an example of how we are going to implement this interface.

View

In our view, We have created a simple window which is depicting a user and has three properties defined on it – First Name , Last Name and Age. Let’s go ahead and create a view model for our simple view.

ViewModel

 Lets create a view model for our User View and name it as UserViewModel. To implement the databinding, lets implement the INotifyPropertyChanged interface. As seen in the code below, we see that for implementing the INotifyPropertyChanged, we have declared a public event PropertyChanged which takes in a delegate method PropertyChangedEventHandler. Now for all the properties which we want to have databinding capabilities, we have gone ahead and provided the event trigger by calling the delegate PropertyChanged.

class UserViewModel : INotifyPropertyChanged
{
    private int _age;
    private string _firstName;
    private string _lastName;
    public event PropertyChangedEventHandler PropertyChanged;
    public UserViewModel(){}
    public string LastName
    {
       get { return _lastName; }
       set
       {
          if (value != _lastName)
          {
             _lastName = value;
             if (PropertyChanged != null)
             {
               this.PropertyChanged(this, new propertyChangedEventArgs("LastName"));
             }
          }
       }
    }
    public string FirstName
    {
        get { return _firstName; }
        set
        {
           if (value != _firstName)
           {
             _firstName = value;
             if (PropertyChanged != null)
             {
                this.PropertyChanged(this, new PropertyChangedEventArgs("FirstName"));
             }
           }
        }
    }
    public int Age
    {
        get { return _age; }
        set
        {
           if (value != _age)
           {
              _age = value;
              if (PropertyChanged != null)
              {
                 this.PropertyChanged(this, new PropertyChangedEventArgs("Age"));
              }
           }
        }
    }
}

To make this code working, we now just need to define these bindings in the User View XAML code and we also need to provide the hook up code between the view and viewmodel.

<TextBox Height="23" HorizontalAlignment="Left" Margin="242,27,0,0" Name="firstNameTextBox" Text ="{Binding FirstName,Mode=TwoWay}" VerticalAlignment="Top" Width="120" Grid.Column="1" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="242,69,0,0" Name="lastNameTextBox" Text ="{Binding LastName,Mode=TwoWay}" VerticalAlignment="Top" Width="120" Grid.Column="1" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="242,115,0,0" Name="ageTextBox" Text ="{Binding Age,Mode=TwoWay}" VerticalAlignment="Top" Width="120" Grid.Column="1" />

As you can see from the code above, we have bound the textboxes with the Properties defined in our UserViewModel class.

Now as a final step , we just need to hook up the View and Model, one way in which we can do this is by creating an object of View Model in our constructor of the view and then setting up the data context of the view as the view model.

UserViewModel viewModel = new UserViewModel();
this.DataContext = viewModel;

Problems with this implementation of the INotifyPropertyChanged.

If we notice it closely, with the approach described above, we have to implement the INotifyPropertyChanged interface on all of our View Models and this would lead to errors as we have to repetitively specify the property name in the event argument which is an string. Let’s look at a better way of implementing the same thing.

 Better Approach : Using NotificationObject of Prism

The Prism Library provides a convenient base class from which you can derive your view model classes that implements the INotifyPropertyChanged interface in a type-safe manner. The base class it provides us is called NotificationObject. Let’s take a look at its implementation.

public abstract class NotificationObject : INotifyPropertyChanged
{
   protected NotificationObject();
   // Summary: Raised when a property on this object has a new value.
   public event PropertyChangedEventHandler PropertyChanged;
   // Summary: Raises this object's PropertyChanged event.
   // Parameters: 
   // propertyExpression:
   // A Lambda expression representing the property that has a new value.
   // Type parameters:
   // T: The type of the property that has a new value
   protected void RaisePropertyChanged(Expression propertyExpression);
   // Summary: Raises this object's PropertyChanged event for each of the properties.
   // Parameters:
   // propertyNames: The properties that have a new value.
   protected void RaisePropertyChanged(params string[] propertyNames);
   // Summary:
   // Raises this object's PropertyChanged event.
   // Parameters:
   // propertyName: The property that has a new value.
   protected virtual void RaisePropertyChanged(string propertyName);
}

In the code above, we see that Prism has defined a class NotificationObject which implements the INotificationPropertyChanged interface.  We also see that it has three overloaded methods defined for Raising the Property Changed , one method takes, the Lambda expression representing the property that has a new value, the second one takes an array of properties that has a new value and the third one is similar to the one which we explained above in our implementation of the INotifyPropertyChanged event which takes in the property name that has a new value.

 Lets implement a new View Model class for our user view , this one will derive from the NotificationObject provided by the Prism.

class UserBindingUsingPrismViewModel : NotificationObject
{
   private int _age;
   private string _firstName;
   private string _lastName;
   public string LastName
   {
      get { return _lastName; }
      set
      {
         if (value != _lastName)
         {
           _lastName = value;
           RaisePropertyChanged(() => this.LastName);
         }
      }
   }
   public string FirstName
   {
       get { return _firstName; }
       set
       {
          if (value != _firstName)
          {
            _firstName = value;
            RaisePropertyChanged(() => this.FirstName);
          }
       }
   }
   public int Age
   {
      get { return _age; }
      set
      {
         if (value != _age)
         {
           _age = value;
           RaisePropertyChanged(() => this.Age);
         }
      }
   }
}

As we can see from the above code, our inherited view model class is now raising the property change event by invoking RaisePropertyChanged using a lambda expression that refers to the property. Using a lambda expression in this way involves a small performance cost because the lambda expression has to be evaluated for each call. The benefit is that this approach provides compile-time type safety and refactoring support if you rename a property. Although the performance cost is small and would not normally impact your application, the costs can accrue if you have many change notifications. In this case, one should consider using the non-lambda method overload.

MVVM Unplugged – Definition, Benefits, Classes and its interactions

Definition
MVVM is an architectural pattern that facilitates the clear separation of the GUI with the logic. It provides a clean separation between application’s user interface, its presentation logic, and its business logic and data by separating each into separate classes. The MVVM pattern is a close variant of the Presentation Model pattern, optimized to leverage some of the core capabilities of WPF and Silverlight, such as data binding, data templates, commands, and behaviors.  

Benefits
The separation of application logic and UI helps to address numerous development and design issues and can make the application much easier to test, maintain, and evolve. It can also greatly improve code re-use opportunities and allows developers and UI designers to more easily collaborate when developing their respective parts of the application.

Some of the benefits achieved by using MVVM are explained in detail below:

  • Concurrent Development: One of the biggest advantage is that during the development process, developers and designers can work more independently and concurrently on their components. The designers can concentrate on the view, and if they are using Expression Blend, they can easily generate sample data to work with, while the developers can work on the view model and model components.
  • Testability: The developers can create unit tests for the view model and the model without using the view.
  • Easy Redesign of the UI: It is easy to redesign the UI of the application without touching the code because the view is implemented entirely in XAML. A new version of the view can easily be worked upon and plugged into the existing view model.

Details
In the MVVM pattern, the UI of the application and the underlying presentation and business logic is separated into three separate classes: the view, which encapsulates the UI and UI logic; the view model, which encapsulates presentation logic and state; and the model, which encapsulates the application’s business logic and data. The view interacts with the view model through data binding, commands, and change notification events. The view model queries, observes, and coordinates updates to the model, converting, validating, and aggregating data as necessary for display in the view. 
The interaction between the classes is explained in the diagram below:
MVVM Class Interactions
Class Interactions Diagram 

Characteristics of the View Class

  • The view in the MVVM pattern defines the structure and appearance of what one sees on the screen.
  • As a thumb rule, one should not put any logic code that needs to be tested by unit test in the View.
  • The view is a visual element. The view defines the controls contained in the view and their visual layout and styling.
  • The view can customize the data binding behavior between the view and the view model by using the Value converters to format the data or by using the validation rules to provide additional input data validation to the user.
  • The view defines and handles UI visual behavior, such as animations or transitions that may be triggered from a state change in the view model or via the user’s interaction with the UI.

Characteristics of View Model: 

  • The view model is a non-visual class and does not derive from any WPF or Silverlight base class.
  • It encapsulates the presentation logic and is testable independently of the view and the model.
  • The view model does not reference the view. It implements properties and commands to which the view can data bind. It notifies the view of any state changes via change notification events via the INotifyPropertyChanged and INotifyCollectionChanged interfaces.
  • The view model acts as coordinator between the view and the model. It may convert or manipulate data so that it can be easily consumed by the view and may implement additional properties that may not be present on the model.
  • It may also implement data validation via the IDataErrorInfo or INotifyDataErrorInfo interfaces.
  • The view model may define logical states that the view can represent visually to the user.
  • Typically, there is a one-to many-relationship between the view model and the model classes.
  • In most cases, the view model will define commands or actions that can be represented in the UI and that the user can invoke. 

Characteristics of the Model Class 

  • The model in the MVVM pattern encapsulates business logic and data. Business logic is defined as any application logic that is concerned with the retrieval and management of application data and for making sure that any business rules that ensure data consistency and validity are imposed.
  • As a thumb rule models should not contain any use case–specific application logic.
  • Mostly the model represents the client-side domain model for the application. It can define data structures based on the application’s data model and any supporting business and validation logic.
  • The model classes do not directly reference the view or view model classes and have no dependency on how they are implemented.
  • The model classes are typically used in conjunction with a service or repository that encapsulates data access and caching.