The aim of this post (and the next) is to provide insight (and code!) into the implementation of WPF-esque commanding patterns using Silverlight technology. Several ICommand implementations, such as the Prism DelegateCommand<T> already exist out in the wild, but fail to address the routing and CommandBinding needs of developers migrating from the WPF platform. The library and samples can be downloaded from here.
Out of the box Silverlight provides minimal support for commanding - on the bright side however it does provide an interface similar to one from WPF to build upon.
Routing in Action
Before diving into technical details, it is probably worth throwing together a typical demo app showing something ‘typical’ one might see in WPF.

The application consists of two ‘DataControls’ (instances of which are contained within the borders) that utilise an implementation of RoutedCommand. In the example below, the command is exposed as a property (as opposed to a field) for databinding purposes (and demonstrates how to get around the lack of x:Static support in Silverlight).
![clip_image002[12] clip_image002[12]](http://blogs.imeta.co.uk/images/blogs_imeta_co_uk/aboyne/WindowsLiveWriter/SilverlightCommandsRoutingandCommandBind_A3FD/clip_image002%5B12%5D_thumb.jpg)
The interesting thing to note here is that the behaviours of the command have not been defined yet - there is no ‘Execute’ or ‘CanExecute’ body provided with the RoutedCommand. In WPF one would typically expect command invocations to bubble up the visual tree until finding something to handle them. The provided Silverlight commanding API provides for a similar effect.
Taking a look at the code-behind for the main page demonstrates how in this instance the SaveCommand is bound to logic. Note how the logic is handled outside of the user control that uses the command.
![clip_image002[14] clip_image002[14]](http://blogs.imeta.co.uk/images/blogs_imeta_co_uk/aboyne/WindowsLiveWriter/SilverlightCommandsRoutingandCommandBind_A3FD/clip_image002%5B14%5D_thumb.jpg)
In a similar manner to WPF, the CommandManager can be used to notify all the commands they should re-evaluate their CanExecute state, and it would be feasible to hook onto events such as keydown/mousemove etc to invoke InvalidateRequerySuggested in a similar manner to WPF for ‘automated’ re-evaluation of command states.
Now we have seen a small demonstration of the framework, let’s take a closer look at the detail.
CommandBinding
![clip_image002[16] clip_image002[16]](http://blogs.imeta.co.uk/images/blogs_imeta_co_uk/aboyne/WindowsLiveWriter/SilverlightCommandsRoutingandCommandBind_A3FD/clip_image002%5B16%5D_thumb.jpg)
CommandBindings are really about being able to separate the invoked actions away from the definition of the command itself.
There are a few things to note here:
· The command in the above example is publically and statically available, but does not have to be.
· The third parameter is optional, if a CanExecute handler is omitted – the framework will assume the command can always execute.
· If the third parameter is supplied, e.CanExecute must be set to true in order for the command to be executable.
· Any number of command bindings may exist for a command.
In practice a CommandBinding enables a command to become context aware once it is associated with something, be it a presenter or view etc. For example, in the snippet below a binding for the ‘ShowAllWorkItemsCommand’ is associated with the ‘shell’; when the ‘shell’ executes that command, those behaviours defined in that binding will be invoked. Other components can provide different bindings for the same command to provide different behaviours, with each component behaving independently even though they are all effectively using the same command.
![clip_image002[18] clip_image002[18]](http://blogs.imeta.co.uk/images/blogs_imeta_co_uk/aboyne/WindowsLiveWriter/SilverlightCommandsRoutingandCommandBind_A3FD/clip_image002%5B18%5D_thumb.jpg)
RoutedCommand
![clip_image002[20] clip_image002[20]](http://blogs.imeta.co.uk/images/blogs_imeta_co_uk/aboyne/WindowsLiveWriter/SilverlightCommandsRoutingandCommandBind_A3FD/clip_image002%5B20%5D_thumb.jpg)
Unlike DelegateCommand<T> provided with Prism, we do not provide the bodies of the behaviours within the command definition itself, as that information is defined in the command bindings (see previous example in CommandRouting). A RoutedCommand defined without any CommandBindings will never execute as CanExecute will return false in those circumstances.
To supplement the ICommand implementation, RoutedCommand adds some concrete methods to allow commands to be context-aware:
![clip_image002[24] clip_image002[24]](http://blogs.imeta.co.uk/images/blogs_imeta_co_uk/aboyne/WindowsLiveWriter/SilverlightCommandsRoutingandCommandBind_A3FD/clip_image002%5B24%5D_thumb.jpg)
So, if a several elements provided different bindings for the same command, calls to these methods will end up being delegated to the respective binding, based on the context passed in.
CommandRouter
So how are the statically defined commands aware of their bindings? This is where the CommandManager and CommandRouter come into play.
Whenever a RoutedCommand queries its state or invokes an action, it requests a CommandRouter from the CommandManager, and delegates its requests to the obtained CommandRouter. The CommandManager exposes a default CommandRouter to provide support for command bubbling similar to WPF. The CommandRouter (an ICommandRouter) can be substituted for any custom routing that may be required; for example, a routing strategy could be introduced to provide support for command tunnelling.
An example of a non-contextual command binding in its simplest form:-
![clip_image002[26] clip_image002[26]](http://blogs.imeta.co.uk/images/blogs_imeta_co_uk/aboyne/WindowsLiveWriter/SilverlightCommandsRoutingandCommandBind_A3FD/clip_image002%5B26%5D_thumb.jpg)
A test demonstrating contextual command bindings:-
ICommandBindingSource
![clip_image002[28] clip_image002[28]](http://blogs.imeta.co.uk/images/blogs_imeta_co_uk/aboyne/WindowsLiveWriter/SilverlightCommandsRoutingandCommandBind_A3FD/clip_image002%5B28%5D_thumb.jpg)
As previously mentioned, the default CommandRouter provides a bubbling effect similar to WPF. The basic mechanics are as follows:-
· When a RoutedCommand is invoked, it delegates the request to the CommandRouter.
· The CommandRouter determines if the passed context supports ICommandBindingSource.
· If the passed context is a UI element, it will walk the parent visual tree until it finds something supporting ICommandBindingSource (e.g. the page).
· Once an ICommandBindingSource is found, it will request the CommandBinding for the Command and execute behaviours accordingly.
An important note regarding realization of ICommandBindingSource is that the bindings do not necessarily have to live on the type implementing the interface. For example, it may the View that implements the interface, but this could easily delegate straight down to an underlying presenter should you prefer to keep the command bindings out of the UI.
Command Behaviour
The commanding infrastructure provided with Prism introduced a neat WPF way of attaching commands to UI elements. A modified implementation of this is provided to allow RoutedCommands to be hooked up in a similar manner. Most of the code from Prism remains unchanged, however changes were required to allow state synchronization with CommandManager.InvalidateRequerySuggested. It is vital therefore when using behaviours to attach commands to visual elements to use the behaviours provided in iMeta.Windows.Commands, otherwise weak references will get collected for the event handlers and the visual elements will not react to CanExecuteChanged.
Conclusion
The provided framework allows for command bubbling, custom routing, centralized management of state change notification and separation of command logic from their definitions. The sample provided may not be an ideal architecture, as many would opt for keeping as much code out of the UI as possible - I will cover an alternative commanding approach with an MVVM spin in my next post. For those WPF developers wanting to migrate existing applications to Silverlight that require command routing (and maybe custom routing), then hopefully this post will be of use.