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.

About Abhinav Ranjan

Technologist | Strategist
Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>