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:

class Client
static void Main(string[] args)
Invoker i = new Invoker();
//save undo to position 100
ICommand a = new UndoCommand(100);
//save undo to position 200
ICommand b = new UndoCommand(200);
//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)
public void AddCommand(ICommand 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:EventTrigger EventName="Click">
<i:InvokeCommandAction Command="{Binding SubmitCommand}"/>

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:EventTrigger EventName="Click">
<i:CallMethodAction TargetObject="{Binding}" Method="Submit"/>

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.

orderCompositeViewModel.SubmitCommand );
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.

Software Architecture

Software Architecture
Software Architecture


Philippe Kruchten, Grady Booch, Kurt Bittner, and Rich Reitman derived and refined a definition of architecture based on work by Mary Shaw and David Garlan (Shaw and Garlan 1996). Their definition is:

“Software architecture encompasses the set of significant decisions about the organization of a software system including the selection of the structural elements and their interfaces by which the system is composed; behavior as specified in collaboration among those elements; composition of these structural and behavioral elements into larger subsystems; and an architectural style that guides this organization. Software architecture also involves functionality, usability, resilience, performance, reuse, comprehensibility, economic and technology constraints, tradeoffs and aesthetic concerns.”

In Patterns of Enterprise Application Architecture, Martin Fowler outlines some common recurring themes when explaining architecture. He identifies these themes as:

“The highest-level breakdown of a system into its parts; the decisions that are Hard to change; there are multiple architectures in a system; what is architecturally Significant can change over a system’s lifetime; and, in the end, architecture boils Down to whatever the important stuff is.”

 Software application architecture is the process of defining and coming up with a solution that is well structured and meets all of the technical and operational requirements. The architecture should be able to take into account and improve upon the common quality attributes such as performance, security, and manageability.

The main focus of the Software architecture is how the major elements and components within an application are used by, or interact with, other major elements and components within the application. The selection of data structures and algorithms or the implementation details of individual components are design concerns, they are not an architectural concerns but sometimes Design and Architecture concerns overlap.

Before starting the architecting of any software, there are some basic questions that we should strive to get answers for. They are as follows:

  • How the users of the system will be interacting with the system?
  • How will the application be deployed into production and managed?
  • What are the various non-functional requirements for the application, such as security, performance, concurrency, internationalization, and configuration?
  • How can the application be designed to be flexible and maintainable over time?
  • What are the architectural trends that might impact your application now or after it has been deployed?

Goals of Software Architecture

Building the bridge between business requirements and technical requirements is the main goal of any software architecture. The goal of architecture is to identify the requirements that affect the basic structure of the application. Good architecture reduces the business risks associated with building a technical solution while a good design is flexible enough to be able to handle the changes that will occur over time in hardware and software technology, as well as in user scenarios and requirements. An architect must consider the overall effect of design decisions, the inherent tradeoffs between quality attributes (such as performance and security), and the tradeoffs required to address user, system, and business requirements.

Principles of Software Architecture

The basic assumption of any architecture should be the belief that the design will evolve over time and that one cannot know everything one need to know up front. The design will generally need to evolve during the implementation stages of the application as one learn more, and as one tests the design against real world requirements.

Keeping the above statement in mind, let’s try to list down some of the Architectural principles:

  • The system should be built to change instead of building to last.
  • Model the architecture to analyze and reduce risk.
  • Use models and visualizations as a communication and collaboration tool.
  • The key engineering decisions should be identified and acted upon upfront.

Architects should consider using an incremental and iterative approach to refining their architecture. Start with baseline architecture to get the big picture right, and then evolve candidate architectures as one iteratively test and improve one’s architecture. Do not try to get it all right the first time—design just as much as you can in order to start testing the design against requirements and assumptions. Iteratively add details to the design over multiple passes to make sure that you get the big decisions right first, and then focus on the details. A common pitfall is to dive into the details too quickly and get the big decisions wrong by making incorrect assumptions, or by failing to evaluate your architecture effectively.

When testing your architecture, consider the following questions:

  • What were the main assumptions that were made while architecting the system?
  • What are the requirements both explicit and implicit this architecture is satisfying?
  • What are the key risks with this architectural approach?
  • What countermeasures are in place to mitigate key risks?
  • In what ways is this architecture an improvement over the baseline or the last candidate architecture?

 Design Principles

When getting started with Software design, one should keep in mind the proven principles and the principles that adheres to minimizes costs and maintenance requirements, and promotes usability and extensibility. The key principles of any Software Design are:

  • Separation of concerns: The key factor to be kept in mind is minimization of interaction points between independent feature sets to achieve high cohesion and low coupling.
  • Single Responsibility principle: Each component or module should be independent in itself and responsible for only a specific feature or functionality.
  • Principle of Least Knowledge: A component or object should not know about internal details of other components or objects.
  • Don’t repeat yourself (DRY): The intent or implementation of any feature or functionality should be done at only one place. It should never be repeated in some other component or module
  • Minimize upfront design: This principle is also sometimes known as YAGNI (“You ain’t gonna need it”). Design only what is necessary. Especially for agile development, one can avoid big design upfront (BDUF). If the application requirements are unclear, or if there is a possibility of the design evolving over time, one should avoid making a large design effort prematurely.

Design Practices

  • Keep design patterns consistent within each layer.
  • Do not duplicate functionality within an application.
  • Prefer composition to inheritance. If possible, use composition over inheritance when reusing functionality because inheritance increases the dependency between parent and child classes, thereby limiting the reuse of child classes. This also reduces the inheritance hierarchies, which can become very difficult to deal with.
  • Establish a coding style and naming convention for development.
  • Maintain system quality using automated QA techniques during development. Use unit testing and other automated Quality Analysis techniques, such as dependency analysis and static code analysis, during development
  • Not only development, also consider the operation of your application. Determine what metrics and operational data are required by the IT infrastructure to ensure the efficient deployment and operation of your application.

Application Layers: While architecting and designing the system, one needs to carefully consider the various layers into which the application will be divided. There are some key considerations that need to be kept in mind while doing that:

  • Separate the areas of concern. Break your application into distinct features that overlap in functionality as little as possible. The main benefit of this approach is that a feature or functionality can be optimized independently of other features or functionality
  • Be explicit about how layers communicate with each other.
  • Abstraction should be used to implement loose coupling between layers.
  • Do not mix different types of components in the same logical layer. For example, the UI layer should not contain business processing components, but instead should contain components used to handle user input and process user requests.
  • Keep the data format consistent within a layer or component.

Components, Modules, and Functions: Key Considerations

In the previous sections we talked about key considerations that need to be kept in mind while architecting or designing an application. We also touched based on what needs to be kept in mind when we are dividing our application into various layers. In this section let’s take a look at some key considerations for designing component, modules and Functions.

  • A component or an object should not rely on internal details of other components or objects.
  • Never overload the functionality of a component. For example, a UI processing component should not contain data access code or attempt to provide additional functionality.
  • Explicitly state how the components will communicate with each other. This requires an understanding of the deployment scenarios your application must support. You must determine if all components will run within the same process, or if communication across physical or process boundaries must be supported—perhaps by implementing message-based interfaces.
  • Keep crosscutting code (such as logging and performance) abstracted from the application business logic as far as possible.
  • Present a clear contract for components. Components, modules, and functions should define a contract or interface specification that describes their usage and behavior clearly.

Technology Blogs
top sites