With the latest release of nRoute we’ve added a trove of navigation-related features, to explain and demonstrate these features I’ve put together an end-to-end application that fronts the Netflix’s oData Catalog. And so in this post we’ll go through using these feature in a step-by-step manner to cumulatively compose a rich, extensible, and loosely-coupled application. Here is what we are going after:

PersonListing

MovieView View the nRoute’s Netflix App (note you can also install the application on your desktop).

Guide Scope

Right off the bat, let me be clear, this post does not show you how to consume oData services or explain how to design iPad’ish UIs or troll on the virtues of MVVM – it purely concentrates on plugging-in nRoute’s navigation and related features to compose our demo app. Familiarity with nRoute concepts is not a must, but will be much helpful. Secondly, just as I finalized this post, Netflix switched from a purely server-side paging-model to a hybrid client-server paging-model so I had to revisit the code, hence there might be a bit of mismatch from what’s shown here and the actual code.

Step 1. Application Setup

For our application we’ll split up the solution into two projects, one the main Silverlight (xap) application and the other a class library which will hold the Netflix service. And so first, in our data project we need to add a service reference to the Netfix oData Catalog.

CatalogService

We also need to need to add references to nRoute, so in both our Silverlight projects we add references to nRoute.Framework.dll, along with its dependencies System.Observable and System.Windows.Interactivity. And lastly you need to cross-reference the data project to the main application project. More...

Posted by Rishi on 30-Jun-10 1:21 AM, 42 Comments

In a MVVM architecture ICommands are the primary abstractions that formalize the exposing and consumption of ViewModel defined functionality for use by its View. However, unlike WPF, Silverlight features no build-in ICommand implementations, supporting infrastructure or out-of-box integration with Controls. So, with this post I'll cover the ICommand-related infrastructure present in nRoute.Toolkit and go-over various aspects related to exposing, consumption and using ICommands in Silverlight.

1. Defining ICommands

Included in the nRoute.Toolkit are two ICommand implementations called ActionCommand<T> and ActionableCommand<T>, they both basically take in a delegate that handles the execution of the command. However, the difference between an ActionCommand<T> and the ActionableCommand<T> is simply that the latter allows you to define a delegated-based predicate that can determine as to if the command is currently executable. Also for convenience sake included are two non-generic versions of the same commands, that specifically relieve you of handling a command parameter.

ICommands

Also as shown above, the featured ICommand implementations provides you with an IsActive property using which you can enable or disable the command. Further, the RequeryCanExecute method allows you to re-evaluate as to if the current command is executable for its consumers. Further, to demonstrate a somewhat realistic use of an ICommand, we'll go-through a scenario from my Web Xcel demo app (shown below), whose code you can actually download from Codeplex.

WebXcel

For our use-case we are going to focus on a "Save Worksheet" functionality that is exposed as an ICommand via a property on the ViewModel. And the basic use-context is that we have this Worksheet Object (visualized as a Grid), which when changed can be saved by calling the "SaveWorksheet" Command, through the "Save Worksheet" Hyperlink Button (shown in the "Document Helper" panel above). Now, in the ViewModel code the SaveWorksheetCommand is declared and instanciated as follows:

   1: // Declare Command
   2: public ActionableCommand SaveWorksheetCommand { get; private set; }
   3:  
   4: // Define Command
   5: SaveWorksheetCommand = new ActionableCommand(() =>
   6: {
   7:     // basic check
   8:     if (this.Worksheet == null || !IsDirty) return;
   9:  
  10:     // update the status
  11:     var _token = StatusViewService.UpdateStatus(SAVING_WORKSHEET_STATUS);
  12:     SaveWorksheet();
  13:     _token.Dispose();
  14:    
  15: }, () => this.Worksheet != null && this.IsDirty)
  16: .RequeryOnCommandExecuted(OpenWorksheetCommand)
  17: .RequeryOnCommandExecuted(NewWorksheetCommand)
  18: .RequeryOnPropertyChanged(this, () => IsDirty);

In line 2, we declare a SaveWorksheetCommand property of type ActionableCommand, note it is the non-generic version and thus takes in no ICommand parameter. On initialization of the ViewModel, the ICommand implementation is instantiated as shown in Line 5. The constructor for the ActionableCommand takes in two parameters, one to define the execute functionality and second to define a predicated as to if the command is currently executable. So with Line 6-to-14 the execution handler basically updates the Status-Bar message (Line 11), then saves the active Worksheet via a helper method called "SaveWorksheet" (Line 12) and then retract the Status-Bar update (Line 13) by disposing the given token. Internally, the SaveWorksheet method serializes the Worksheet Object to a xml file and allows the user to save by showing a Save File Dialog. 

Also you can see in Line 8, we pre-check that the Active Worksheet to save is not null and that it has one or more pending changes (i.e. is dirty). That pre-check logic is basically the same logic that defines as to if we can execute the Save Worksheet command, and so in Line 15 the lambda statement defines the exactly same logic as the second parameter to the ActionableCommand constructor.

2. Defining ICommand Dependencies

As I hope is apparent, creating ICommands in your ViewModel is very straightforward but there is one aspect to that is rather cumbersome - the problem is that a command's execution is subject to a number of direct and indirect dependencies, and so whenever a dependency changes we must re-evaluated the current execution status of the command. In practical terms this means that dependencies should use the "RaiseQueryCommand" method to effect a CanExecuteChanged event, which tells an ICommand's consumers to check the executable status vis-a-vie the CanExecute method on the ICommand.

As you can image this is not only cumbersome but it also leads you to implicitly-defined ICommand dependencies throughout your code. So, with the nRoute.Toolkit's ICommand implementations we have a set of extension methods that you can use to explicitly define the dependencies, and using the same it also automatically updates any changes to the executable state of the ICommand. If this sounds fancy, it is not - lets look at our SaveWorksheetCommand example. In Lines 16-18 we explicitly define three cases that say re-query the executable status of the command whenever either of the OpenWorksheetCommand or NewWorksheetCommand commands are executed (because if we have just created or opened a Worksheet then there is nothing to save). And the third statement says that also re-query whenever the IsDirty property on "this" ViewModel changes (if Worksheet is Dirty, then the save status must have changed). So, now with these three extension methods the command's execution status is automatically re-evaluated, whenever either of the three explicit conditions occur.

Below is the list of the five included extension methods that help define dependencies on ICommands - however, do note you can write your own similar extension methods too (for more information, please see this post).

  • RequeryWhenExecuted - this methods basically says that whenever the command itself executes then re-query it's execution state.
  • RequeryOnCommandExecuted - as shown above, this one re-queries the command whenever some other command is executed
  • RequeryOnCommandCanExecuteChanged - this extension method says whenever the executable status of a another specified command changes then do a re-query
  • RequeryOnCollectionChanged - this pegs the re-query on a given collection changing, wherein the collection implements INotifyCollectionChanged
  • RequeryOnPropertyChanged - this extension as we have seen, begets a re-query when a INotifyPropertyChanged implementing object's property changes

ExecuteCommandBehavior 3. Consuming ICommands

As far as consuming ICommands is concerned, we are thoroughly-thoroughly covered by a so-named ExecuteCommandAction behaviour in the nRoute.Toolkit. And if you are wondering as why it is double-so-thorough, well because of three reasons besides the simple fact that it can execute commands. Reason one, even though the Silverlight framework itself does not support binding to Dependency Properties, with the ExecuteCommandBehavior you can bind to commands defined in your ViewModel - just remember you have to use the Binding post-fixed properties as shown in the Blend screenshot above. To know more about this so-called dual-property binding for Silverlight, please see my earlier post introducing nRoute.Toolkit. Similarly, you can also bind the parameter by using ParameterBinding property or alternatively statistically specify the parameter using the Parameter property.

Reason two, the execute command behaviour is implemented as a TriggerAction - what does that mean, it simply means you can pair it with any kind of Trigger (note, the Trigger and TriggerAction are from the Blend SDK). So the pairing can be done with an Event Trigger or a MouseWheel Trigger or a Gesture Trigger, in fact you can create your own trigger - like say one that responds to Voice Input. The benefit to all this Trigger-TriggerAction separation is that your use of a command is not limited to certain a set of pre-defined use-cases, which I think helps with both reusability and flexibility. So for example, with the SaveWorksheetCommand I've used the ExecuteCommandAction with two types of triggers.

   1: <!-- ICOMMAND WITH KEY STROKES -->
   2: <i:Interaction.Triggers>
   3:     <nTriggers:KeyTrigger WithControlModifier="True" Key="S" WithShiftModifier="True">
   4:         <nBehaviors:ExecuteCommandAction CommandBinding="{Binding SaveWorksheetCommand}"/>
   5:     </nTriggers:KeyTrigger>
   6: </i:Interaction.Triggers>

Above, we are pairing the KeyTrigger (for key-set Ctrl+Shift+S) with the ExecuteCommandAction behaviour that triggers the SaveWorksheetCommand in our ViewModel. And below we are pairing the same command behaviour with an EventTrigger to raise the command on a click event of a Hyperlink Button. Now, the XAML might look dreadful, but don't worry all this can be done visually in Blend - which will spit out the same XAML you see below.

   1: <!-- ICOMMAND WITH Click EVENT  -->
   2: <HyperlinkButton Content="Save Worksheet">
   3:     <i:Interaction.Triggers>
   4:         <i:EventTrigger EventName="Click">
   5:             <nBehaviors:ExecuteCommandAction ManageEnableState="True"
   6:                 CommandBinding="{Binding SaveWorksheetCommand, Mode=OneWay}" />
   7:         </i:EventTrigger>
   8:     </i:Interaction.Triggers>
   9: </HyperlinkButton>

4. Managing ICommand Control States

The third reason as to why the ExecuteCommandAction is thorough is that it allows you to control the enabled/interactivity state of the control it is applied on - by using the "ManageEnabledState" option (see the Blend screenshot above). What does that mean, it simply means that if the command's not executable it will disable the control for you - so for example in our SavewWorksheetCommand example, if there is no Active Worksheet or if the Active Worksheet is not dirty the Hyperlink Button will be disabled (see Line 5 in the XAML snippet above that enables this scenario by setting the ManageEnabledState to true).

WithPendingChanges NoPendingChangess

The picture on the left shows the Hyperlink Button disabled when there are no pending changes to the Active Worksheet, whereas the picture on the right shows an enabled Hyperlink Button when there are pending changes - the same is also indicated by the asterisks in the title. The enabling/disabling is done for you automatically (once you opt in the ManageEnabledState option), as the behaviour listens for changes in command's executable status and evaluates its use status against the command. Further, the ExecuteCommandAction behaviour also also plays nice with controls that don't have an IsEnabled (ie. non-Control type derived controls) property by taking away their interactivity. In the screenshot below, the Border Control doesn't support an IsEnabled property, however when the attached command is not executable the Border Control is dimed down and its interactivity is taken away.

ButtonVsBorderControl

5. Relaying ICommands

Now one of the other common problem you will find with ICommands is related to consuming it with templated controls like ItemsControl or ListBox Controls in Silverlight. The underlying issue is that from within a DataTemplate you can't access the ViewModel and hence the ICommands are not addressable. The reason is simple, because a DataTemplate's DataContext is set to the item being enumerated - so if a customer item is being enumerated, then that would be set as the active DataContext. So how do we solve this problem, the answer is simple - we first create a command relay as a resource in our View and then bridge the relay with an actual implementation from our ViewModel. Note, the command relay will be a static resource and thus can be "binded" as such.

Lets consider a simple example, lets say we have a ItemsControl that lists Customers collection from our ViewModel - it uses a DataTemplate that needs to consume an EMailCustomerCommand which is also defined in our ViewModel. So here is what we do, we first define an EMailCustomerCommandRelay in our View's resources collection and then use a BridgeCommand behaviour to source the relay from our ViewModel via Binding. Below is the relevant XAML:

   1: <!-- DECLARE RELAY -->
   2: <UserControl.Resources>
   3:     <nComponents:CommandRelay x:Key="EMailCustomerCommandRelay" />
   4: </UserControl.Resources>
   5:  
   6: <!-- BRIDGE THE RELAY FROM THE VIEWMODEL -->
   7: <i:Interaction.Behaviors>
   8:     <nBehaviors:BridgeCommandBehavior 
   9:         CommandRelay="{StaticResource EMailCustomerCommandRelay}"
  10:         CommandSourceBinding="{Binding EMailCustomerCommand, Mode=OneWay}"/>
  11: </i:Interaction.Behaviors>

Once we have done this, all we need to do is to use the CommandRelay in our DataTemplate as a StaticResource (see below). Also note we are passing the Active DataContext (which would be the Customer Object) as the Parameter to the ICommand:

   1: <DataTemplate x:Key="CustomerDataTemplate">
   2:     <StackPanel>
   3:         <TextBlock Text="{Binding CustomerName, Mode=OneWay}"/>
   4:         <Button Content="E-Mail Customer">
   5:             <i:Interaction.Triggers>
   6:                 <i:EventTrigger EventName="Click">
   7:                     <nBehaviors:ExecuteCommandAction 
   8:                         Command="{StaticResource EMailCustomerCommandRelay}"
   9:                         ParameterBinding="{Binding Mode=OneWay}"/>
  10:                 </i:EventTrigger>
  11:             </i:Interaction.Triggers>
  12:         </Button>
  13:     </StackPanel>
  14: </DataTemplate>

Now, remember this is all doable in Blend, so it's really quite simple once you get past declaring the relay and bridging the ICommand steps. For our sample scenario discussed above, you can download the Blend Project including the ViewModel part that is consumed by the CommandRelay.

Relay Commands in Blend

Summary

In summary, I've show how the ICommand related infrastructure in nRoute.Toolkit helps you to define, consume, manage and use ICommands in Silverlight. Further, given how central ICommands are to MVVM we have a feature-rich implementation that helps with both View and ViewModel sides of the divide, and also overcomes most of the platform-level shortcomings in Silverlight.

Download the nRoute.Toolkit from Codeplex
Download the Relay Command Project Source (note, require the toolkit dll)

Posted by Rishi on 03-Nov-09 8:28 AM, 26 Comments

Categories: nRoute, nRoute

ViewServices in nRoute are basically UI implemented functionality exposed as services for non-visual consumption - think a Status-Bar as IStatusInfo service. The underlying idea is separation of concerns, so that non-visual components like ViewModels don't have to take dependency on View-based controls or on platform specific contraptions. Now, there is nothing radical about this concept, but with nRoute we get first-class API support to specifically identify, implement and consume "ViewServices" and that's what is discussed in this post.

To demonstrate ViewServices I've put up a small demo called Web Xcel - it replicates the Office Web look and feel for a spreadsheet type application. However, it is no spreadsheet; I've just used the feel of a potentially real application to show how we can integrate and consume ViewServices in an application's flow as it were. Below are some screenshots:

Web Xcel

Web Xcel

You can view the Web Xcel demo app here.

ViewServices - The Basics

Before we get to some examples of ViewServices let me just briefly recap how to define and consume ViewServices - for a proper introduction see the introductory post to nRoute.Toolkit. Firstly, the functionality that a ViewService exposes is encapsulated in a contact i.e. an interface. The defined interface, is then implemented onto a control/object which we earmark with a MapViewService attribute along with some related options. So for example, in Web Xcel demo we have this IConfirmMessageViewService contract that allows us to confirm "something" from the user, the interface definition looks like:

   1: public interface IConfirmMessageViewService
   2: {
   3:     string Title { get; set; }
   4:     string Message { get; set; }
   5:     IDisposable Confirm(Action<bool?> confirmationCallback);
   6: }

This contract basically takes in a title, message and a callback that returns the response from the user - we'll get to the details ahead. However, this contract's implementing class is decorated with the MapViewService attribute as shown below:

   1: [MapViewService(typeof(IConfirmMessageViewService), 
   2:     Lifetime=ViewServiceLifetime.PerInstance)]
   3: public class ConfirmationViewService
   4:     : IConfirmMessageViewService
   5: {
   6:     // implementation 
   7: }

Now, the only notable thing with MapViewService attribute is the Lifetime option which tells nRoute how/when to instantiate/serve a request of the IConfirmMessageViewService - and in this case, it is going to instantiate a new instance per request. You have other lifetime management options namely singleton, weak singleton, discovered instance and self-registered instance. Singleton obviously means a single instance for all requests and the weak singleton option serves a single instance around as long one or more consumers are using it, once it is out of use it's GC'ed. The discovered instance in interesting, as it goes through the VisualTree to find the first implementing instance and returns what it finds. And the self-registered ViewService relies on an implementing control to register an instance of itself when available and unregister when going dark. The important thing to remember with these non per-instance options is the effect on state-management of having potentially multiple concurrent consumers as opposed to each consumer having their own instance.

To resolve a ViewService, we can make use of the ViewServiceLocator helper class that like any IoC component returns an instance. Also in cases where we have more that one implementation of a ViewService we can name each implementation and resolve the same by identifying its name. Now, to use the IConfirmMessageViewService we do something like:

   1: // set up the service
   2: var _showMessageVS = ViewServiceLocator.GetViewService<IConfirmMessageViewService>();
   3: _showMessageVS.Title = MODIFIED_WORKSHEET;
   4: _showMessageVS.Message = CONFIRM_WORKSHEET;
   5:  
   6: // we get the user's response
   7: return _showMessageVS.Confirm(confirmationCallback);

The idea behind the use above is to confirm from the User as to if we save the active worksheet, which has pending changes, before we open or create another worksheet. The visual implementation uses a dialog, as shown below, which confirms for the ViewModel how to proceed. 

Confirmation Child Window

The larger point to ViewServices is that your ViewModel is not concerned about how the visually-implemented functionality is rendered or responded to. It disconnects the implementation from its consumption, so for example you could change or put up a totally new visual implementation, and your ViewModel will be none-the-wiser but more importantly it won't have to be changed.

Web Xcel Demo's ViewServices

I'm not going to go through the full details of the ViewServices in the demo app (you have the code for that), but I'll just describe them and highlight some of the more interesting parts.

IOpenFileViewService

This ViewService is part of the toolkit itself, and as it self-suggests it opens a file dialog that returns a file stream. It is really simple, except the notable instruction is that that its use has to be instantiated directly by a user action such as a key press or a click event. Secondly, this is also very important, we can't open two back-to-back dialogs with a single user-interaction - so we can't save a file and follow it by a open file dialog, this manifests in an interesting solution in the demo app.

ISaveFileViewService

This ViewService does as it reads, and is also pre-packaged in the toolkit. One important distinction I'd like to make with this ViewService is that, it is not an "integrated-visual" in a sense that a Status-Bar is. It, like with other dialogs and ChildWindows, is extraordinary in the sense that it somehow appears from sky as opposed to being part of the VisualTree. This distinction makes a difference in how an instance of the specific ViewService is initialized, instantiated and returned - so a Status-Bar in the VisualTree may need to be registered/discovered whereas a Save File Dialog can be new'ed up.

IConfirmMessageViewService

I've already described this ViewService above, and as duly noted it makes use of a ChildWindow. The interesting part of this ViewService is that it takes in a delegate-based callback and returns an IDisposable. The IDisposable is like a token that be used to dispose the dialog - so in some cases when you want to say draw-down the dialog (from your ViewModel) before the user has addressed it, you can call the dispose method on the token. This pattern is also useful in cases when you want to show information-based dialogs like "Uploading" that users can cancel or when finished it can be disposed via your ViewModel. Again, note this an example of non-integrated visual - it falls from the sky.

IStatusViewService

This ViewService is used to update the current "status" of the application, basically visualized via the Status-Bar (so it's an example of an integrated ViewService). The defining interface to this ViewService is very simple, have a look:

   1: public interface IStatusViewService
   2: {
   3:     IDisposable UpdateStatus(string status);
   4: }

Again like the confirmation ViewService this ViewService returns an IDisposable token that can be used to call-off your status update. So for example, when done saving you can trigger the dispose on the token and the status-bar will revert to its default message. However, if another update has been received post yours, the dispose is auto-magically called for you by the status-bar itself - so in that case the token wouldn't do anything. In this way, it can support multiple updates to the status whilst having only one retractable-update active. As a side-note, you have to be careful about the given implementation in the Demo as it can lead to memory-leaks if you indefinitely hold onto the token - so always dispose them or change the implementation to a weakly-referenced one.

IDocumentInfoViewService 

The Web Xcel is like an example of a Single Document Interface (SDI), and to abet that this ViewService helps with updating the title and 'IsDirty' status of the working document. Obviously the implementation of this is very simple here, but the point made is how a ViewModel that that manages the active worksheet can visually reflect the status in the Shell. Secondly, this ViewService (like the IStatusViewService) is directly implemented in the code-behind of the MainPage.xaml (i.e. the Shell also the RootVisual). I am not sure if the MVVM cops would like this, but to me this a UI detail and it can be implemented in the View itself.

Balloon Notification ITimeoutNotificationViewService

This ViewService is implemented as a notification balloon, as shown in the screenshot. It has two main features, one that it supports a timeout of your notifications - so basically it shows the balloon for the given period of time and then closes it. Secondly, it also supports queuing of notifications - so whilst a single notification is being shown it queues the the others and plays them one-by-one in a first-register-first-shown manner. Now, this ViewService is implemented as a control, which I find to be a reasonable way to component'ize and expose ViewServices .

IInteractiveNotificaitonViewService

This ViewService like it suggests allows for a visual notification with an interactive capability in that if the user "interacts" with it, a callback notifying the same is raised. As far as the consumer (like a ViewModel) is concerned the "interaction" is an implementation detail - which in Demo's case happens to be a click on a header-type panel.

  Header Notification

So above, if the User happens to click on the yellow header bar - it would raise a callback saying the user interacted with the message and so do your thing. On the other hand, if the close button is pressed the callback would return saying that the user did not "interact" so do the other thing. Also, because this ViewService is practically a single-instanced (it self-registers itself) service that potentially serves multiple concurrent-consumers, the notifications are queued in a FIFO manner to ensure User's individual viewership for each and ever notification.

ViewServices - Not There Yet

So in this post and accompanying demo we've covered how ViewServices help us to abstract, expose, and consume visually-implemented functionality. This in my experience is an important and often ignored piece of the MVVM puzzle, which I hope by semantically capturing in a ViewService implementation provides for a better handle. However, there are lots of other aspects to this, especially in relation to View-Composition and that is something that needs more work. For example, how can we get contextual tabs integrated into the ribbon when a User is say editing a cell - obviously, you can do it (with something like Prism regions), but what is needed (or what I want) is to keep the View-composition logic out of the ViewModel/Modules and have a XAML-based way to dynamically integrate/compose bits and pieces of the UI together.

Also, some of the other things I want to provide is a generic modal-dialog strap-up that fuse nicely with ViewModels akin to what Nikhil Kothari showed in his post, but for a broader spectrum of uses such as Wizards. Now, some of the solutions would require the full nRoute which avails the routing engine and view-composition capabilities - obviously because the wheel has already been invented there. Other than that, currently we're not doing dependency injection which is big-problem and I want to address it quickly - there are some tricky problem to it making it play nice.

In many ways, a lot of these things are still fresh from the oven - so going forward I'd like to have more scenarios-covered with better formalization of the View-ViewModel interaction.

View the Web Xcel Demo here.
Download the demo app source-code and the nRoute.Toolkit from Codeplex
(note you require the accompanying nRoute.Toolkit dll)

Icons in the demo app are from the Silk Icon collection by Mark James (Thanks).

Posted by Rishi on 23-Oct-09 5:56 AM, 29 Comments

Categories: nRoute, Silverlight

nRoute Toolkit is basically a packaging of some components from the next drop of nRoute - I thought some of the components had merit beyond the nRoute framework, so I packaged them separately in a smallish 50K toolkit. The Silverlight only toolkit features Bindable Dependency Objects, Bindable Triggers, Actions and Behaviours for Blend, an IObservable-based Messaging Framework, a Resource Locator Framework, Module Components, Service Components, ViewModel Components, ViewService Components, Weak Eventing Handlers, Action ICommands and a number other bit and pieces useful for MVVM style development.

I hope to have this introductory post as a semi-documentation for the toolkit and its features, so please bear with me as it does get long. Secondly, the next drop of nRoute will essentially be a superset of what's in this toolkit - namespaces and all will remain the same, however the toolkit doesn't include any routing or navigation related features.

Bindable Dependency Objects

One of the biggest pain point with Silverlight, as of version 3, is that it only supports binding on FrameworkElement derived objects - which in effect limits binding to "visual components" - and therefore "inline" elements don't get the benefit of binding. Now, what I have here is not a perfect solution but a pretty workable one, and I refer to it as attached-bindings because it attaches the binding on any FrameworkElement derivatives (even non-hierarchically related).

The trick in play here is that you have to expose and consume the binding as a System.Windows.Data.Binding type. So for instance, say we have a Dependency Object derived class that has a ordinary "IsReady" dependency property; now, to make it bindable using attached bindings, we have to use what I call a dual-property pattern - wherein we expose the property "normally" but also have another property (post-fixed with the Binding word) of type Binding that is used to bind to the dependency property. Have a look below, note 'GetAttachedBinding' and 'SetAttachedBinding<T>' are extension methods:

   1: public bool IsReady
   2: {
   3:     get { return Convert.ToBoolean(this.GetValue(IsReadyProperty)); }
   4:     set { this.SetValue(IsReadyProperty, value); }
   5: }
   6:  
   7: public Binding IsReadyBinding
   8: {
   9:     get { return this.GetAttachedBinding(IsReadyProperty); }
  10:     set { this.SetAttachedBinding<bool>(_frameworkElement, IsReadyProperty, value); }
  11: }

Given the above, to bind we use the binding syntax against the 'IsReadyBinding' property, while to read the current value of we use 'IsReady' property. If you don't want to use bindings, the IsReady property works just as before and everything else remains the same. The critical part to enable attached bindings is to have a FrameworkElement derivative element to attach too, as represented above by the '_frameworkElement' variable - without this it wouldn't work. But once you have that you can have as many attached-bindings appended to it as you like, it doesn't matter. Secondly I understand having an additional property for each bindable property is not ideal, but it's a working solution and is kind of akin to the async post-fix we already use. Plus, with the extension methods shown above this is not that intrusive of a methodology, especially since you don't need do anything more than create an additional property declaration per dependency property.

Now there are a lot of uses for this, and using this infrastructure included in the toolkit are extensions to the Blend behaviours framework as we'll see right ahead - this also happens to be my favourite new feature in the toolkit.

Bindable Behaviors, Actions and Triggers 

In the first drop of nRoute I did a lot of work on behaviours, in fact I did create something very similar to what is available in Blend but didn't generalize it using triggers, rather per my preference of strong-typed stuff, I created many-many statically declared attached properties to expose/use behaviours. But part of the reason was also that inline dependency objects could not be bound in Silverlight, where as attached properties declared directly onto any FrameworkElement derivate could be. Now, with the binding infrastructure given above and fantastic tooling support in Blend, I choose to dump my behaviour's framework and extend the behaviours and triggers framework made available with the Blend SDK - essentially by making them bindable. This really makes for some fantastic possibilities, because we can now use and consume behaviours that are directly bound to our ViewModel or have them react to property changes through the richness of binding in Silverlight.

In the nRoute.Behaviors.Interactivity namespace you will find four classes that extend the behaviours, trigger actions and triggers in the Blend SDK, with bindable base classes.

BindableBehaviors

The binding-enhanced base classes (below the red-line) give you wrappers around the attached binding solution, and a very important capability to set bindings even when the "AssociatedObject" is not available (it stores and applies the binding to it when the object is attached). So for example, if we had the IsReady property sampled above exposed in any of the above behavior/trigger classes we would write the same as:

   1: public bool IsReady
   2: {
   3:     get { return Convert.ToBoolean(this.GetValue(IsReadyProperty)); }
   4:     set { this.SetValue(IsReadyProperty, value); }
   5: }
   6:  
   7: public Binding IsReadBinding
   8: {
   9:     get { return base.GetBinding(IsReadyProperty); }
  10:     set { base.SetBinding<bool>(IsReadyProperty, value); }
  11: }

As you can see in Line 9 and 10 we are using the base-class based GetBinding and SetBinding methods, they do the attach-binding business underneath. So quite simply, to make your behaviour/trigger/trigger-action property bindable you just need to additionally write something similar to lines 7 to 11 and that's it. Also, with this you can use all the UI facilities in Blend to set the bindings as usual, alternatively if you wanted to bind to static resources you would use the non-binding version (ie. IsReady and not IsReadyBinding). The binding-enhanced base classes are there for your own use, but I've also included some commonly needed behaviours, triggers, and trigger-actions some of which are detailed below.

Value Triggers

Value triggers are Blend-SDK based triggers that fire when a given property's value matches a given criteria - for example, you could use a ValueTrigger to show a special discount animation when when the total cart amount exceeds $1000 in your ViewModel. You can also use this with UI controls, like match some value in a text box and trigger a command in your ViewModel.

In many ways ValueTriggers are central to MVVM, because to my understanding in a MVVM architecture data changes are the primary ViewModel-based mechanism that effect changes in View, and for the other side of the equation data changes and ICommands are the two View-based mechanisms that effect changes in the ViewModel (see the diagram below). Events are not used, because they are a form of direct-coupling - and so there is a total reliance on the SL binding infrastructure for the loosely-coupled glue that makes it all possible. Further for me, this minimal scope of connections is both the beauty and the practical stick that keeps the ViewModel and View independent of each other despite the fact they are intimately interwoven.

ViewViewModelSignifiers

Given the concept above, the practical problem in SL today is consuming the data-changes to effect logical changes in your application, value changes in the controls such as text value is 100% supported but changing the logical state is not. And this is where the ValueTriggers come into play, by combining binding, triggers and trigger-action we can effect logical changes in the View such hiding something or moving something. Next, I'll go through the five value triggers available in the toolkit - just keep in mind you can pair this up with just about any trigger-action or behaviour.

ValueMatchTriggerValueMatchTrigger

Basically it allows you trigger an action when a given source's value equals to another specified value - in the example shown from Blend, the value must match the specified "nRoute" value and then only will it trigger the associated action. Also, the source binding is coming from a ViewModel and we're matching it against a static word but you could match it against anything bindable by using the ValueBinding property. Also note any changes in the Source Binding triggers a re-evaluation of the condition. Alternatively, if you require it not match the specified value then you can negate the result, by using the negate checkbox. The xaml for this example looks like:

   1: <nTriggers:ValueMatchTrigger SourceBinding="{Binding Key, Mode=OneWay}" Value="nRoute">
   2:     <nBehaviors:SetPropertyAction PropertyName="Foreground" Value="#FFFF0000"/>
   3: </nTriggers:ValueMatchTrigger>

Note, by default in Blend the Value property wouldn't be editable, in that case you might have to append it via xaml directly - I hope to create Blend designer extension soon to rectify this.

ValueNullTrigger

This is similar to the ValueMatchTrigger in that it exclusively looks to match the source value to a null. You can also negate this, so that it matches a non-null value. This is really useful when tracking asynchronously loaded data, for example when loaded items list in not null, we could visually effect the UI to indicate the availability of the data. Below is an example of this in xaml:

   1: <nTriggers:ValueNullTrigger SourceBinding="{Binding Key, Mode=OneWay}" Negate="True">
   2:     <nBehaviors:SetPropertyAction PropertyName="Foreground" Value="#FF23FF18"/>
   3: </nTriggers:ValueNullTrigger>

ValueCompareTriggerValueCompareTrigger

Most data comparisons boil down to equals to, greater than, less than or their negated comparisons - and so in addition to earlier mentioned triggers, the ValueCompare trigger allows you to value comparisons with >, >=, ==, !=, <, <= equality operations. For comparison purposes it relies on source value implementing the IComparable interface or you specifying an IComparer implementation.

In the screenshot from Blend show on the right, we compare some Source Value bound from a ViewModel being greater or equal to ten - which triggers the specified trigger action. In xaml the same thing would look like:

   1: <nTriggers:ValueCompareTrigger SourceBinding="{Binding Value, Mode=OneWay}"
   2:     Equality="GreaterThanOrEquals" Value="10">
   3:     <nBehaviors:SetPropertyAction PropertyName="Foreground" Value="#FFFF4321"/>
   4: </nTriggers:ValueCompareTrigger>

Note how dual properties pattern I mentioned earlier, makes everything bindable in Blend but in a bit more extraneous way than normal. Also note the possibility of negating the comparison result, with the negate option.

ValueChangedTrigger

As the name suggest this trigger executes every time its source value changes - which at times is all you need. The xaml example below triggers an animation whenever the value changes:

   1: <nTriggers:ValueChangedTrigger SourceBinding="{Binding Key, Mode=OneWay}">
   2:     <im:ControlStoryboardAction Storyboard="{StaticResource FlashTitleStoryboard}"/>
   3: </nTriggers:ValueChangedTrigger>

ValueSwitchTrigger

Just as in procedural code the switch-cases pairing allows you selectively trigger one or more actions if the Source value matches the Case value. Have a look at a xaml example, first:

   1: <nTriggers:ValueSwitchTrigger SourceBinding="{Binding Value, Mode=OneWay}">
   2:     <nBehaviors:SetPropertyAction nTriggers:ValueSwitchTrigger.CaseValue="1"
   3:         PropertyName="Foreground" Value="#FFFF4321"/>
   4:     <nBehaviors:SetPropertyAction  nTriggers:ValueSwitchTrigger.CaseValue="2"
   5:         PropertyName="Foreground" Value="#FF23FF18"/>
   6: </nTriggers:ValueSwitchTrigger>

In this example we are binding to some "Value" property from our ViewModel, and below are two actions each with a specified case value (using the ValueSwitchTrigger.CaseVale attached property). Now, if the value is one, the first trigger action will be activated, and if value is two the second trigger action will be used. I think it is really simple, yet very powerful and makes use of the all binding goodness in Silverlight.

KeyTrigger KeyTrigger

The KeyTigger is not part of the value-related triggers, all the same it a very useful trigger that responds to keyboard events. Now, I understand there is already an existing KeyTrigger in Blend, but before I found it I had already created this one and I've kept it because it helps with some advance scenarios.

More or less it is all self explanatory, except you can check for more than one modifiers - so a Control+Shift+V can be checked for. Also, you can negate the result to be everything except the keystrokes you have specified, and believe me this is useful. You can also throttle the key inputs by specifying a duration within which only a single key stroke will be processed - again this really useful and recently I had a situation where the UI couldn't keep up with keystrokes so I throttled the user's input and it worked like a charm. Lastly, you can also specify the max number of key strokes past which it will disable the triggering - useful for perhaps limiting baby smash torture.

MouseWheelTrigger.cs MouseWheelTrigger

The MouseWheelTrigger is not like a scrolling solution, it is a trigger which fires when the MouseWheel turns and you can then use it to invoke an action such as scrolling or index change. Also it passes through a delta value, which is factored by whatever you have specified in the DeltaFactor property (the default as shown is 120). And like the KeyTrigger you can throttle the mouse wheel events by defining a time-duration to allow-in a single wheel event.

Trigger Actions

SetPropertyAction I've only included four trigger-actions in this Toolkit, yet I've found them to remarkably useful particularly because they make of the of the binding.

The first of the four triggers is SetPropertyAction, which you've seen being used above - and as the name suggests, it is used to set a property value on the applied element with a specified value. Now, there is something similar already in Blend, but herein we get the possibility to set a binded value - which opens it up to your ViewModel's usage. In the blend screen grab on the right we are setting the text property to a value from our ViewModel, when the associate trigger invokes the action. Also if you just wanted to set the value statically use the non-binding Value property.

Quite similar to the SetPropertyAction is the TargetedSetPropertyAction, using which you set value on another element (ie. the target) as opposed to the declaring element itself. For example:

   1: <i:EventTrigger EventName="Click">
   2:     <nBehaviors:TargetedSetPropertyAction TargetName="BackgroundRectangle"
   3:          PropertyName="Fill">
   4:         <nBehaviors:TargetedSetPropertyAction.Value>
   5:             <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
   6:                 <GradientStop Color="#FFB8EBFF" Offset="0.762"/>
   7:                 <GradientStop Color="White"/>
   8:             </LinearGradientBrush>
   9:         </nBehaviors:TargetedSetPropertyAction.Value>
  10:     </nBehaviors:TargetedSetPropertyAction>                        
  11: </i:EventTrigger>

In the xaml above we are setting the "Fill" property on a Rectangle type element named "BackgroundRectangle" upon a click event. Again by using this with value triggers and binding you get a really powerful tool in your hand, and for the most part this is all Blendable. I will discuss the other two triggers action, in relation to other features because they are related.
 
Behaviours (or Behaviors if you prefer)

I've included four generalized behaviours, in addition to some feature specific ones, and they resolve around the idea of having an element viewable depending on the source being null or not null, or based on some true/false evaluation. This is really useful, in scenarios where you are loading data asynchronous and parts of UI are to be viewable per the availability of data.

So the first of these behaviours is called the BoolValueVisibilityBehavior, which make the targeted element visible if the given bool Value is true else the visibility is set to collapsed. You can negate this behaviour by using the negate option, like before. Similarly, the NullValueVisibilityBehavior sets the visibility to collapsed if the given value is null else it sets it to visible. This is again is negatable, and the value you evaluate against is bindable because it uses BindableBehavior<T> base class mentioned before.

For example, consider we have a search bar we don't want to show until some data is loaded into a ListBox, and so we could attach the following behaviour that tracks as to if the Items property from the ViewModel is null or not. And because we are using dependency properties we listen to data changes, so say if the data is re-loading then the toolbar will automatically hide and show-up when the data has been loaded again.

   1: <i:Interaction.Behaviors>
   2:     <nBehaviors:NullValueVisibilityBehavior ValueBinding="{Binding Items, Mode=OneWay}"/>
   3: </i:Interaction.Behaviors>

NullValueInteractivityBehavior I find the above very useful, but there is a very significant side-effect to setting the visibility to collapsed in that it "shutsdown" the element from processing visual changes. And so for example, if you were to put a NullValueVisibilityBehavior onto a ListBox and wanted to have it viewable once the ItemsSource is set - the items wouldn't show up because when collapsed it wouldn't have process any UI changes - and rightly so.

Now how do deal with that, well firstly we make an element non-viewable by setting its opacity to zero. However, the ListBox could still process mouse events, which is a problem especially if it unknowingly to the user triggers some changes and yet the element is not visible to the user. The second, step to rectify this is to set its IsHitTestVisible property to false - which makes the element non-interactive and yet the UI changes will be processed underneath.

Now, by combining the two solution above I've packaged them as interactivity altering behaviours called BoolValueInteractivityBehavior and NullValueInteractivityBehavior - which like their visibility counterpart, can used to make an element non-viewable though in this case they are capable of processing UI changes. However note this is not a perfect solution, because an element could still possibly handle keyboard triggered changes, if it had the focus. Nonetheless, in a lot of scenarios this works out just fine but be careful of the caveat. And just like before, you can inverse the workings of all these behaviours by using the negate option.

IObservable-based Messaging Framework

Recently, with the Silverlight Toolkit there was a hidden gem shipped by the name of Rx Framework, which you can read about extensively here. Basically, the idea behind it is that by using the observable pattern you can do "reactive programming", kind of like event handling. But the twist is that you can turn past, current and future "observed items" into a persuado data source, which opens it using LINQ to process, shape and consume the observed data. Think event stream processing, as opposed to a pipeline model - and the items are like an IEnumerable being pushed as opposed to being pulled. I am not gonna discuss the reactive framework here, but it is really cool and you should definitely check it out if you still haven't.

In relation to the Rx Framework, what I've done is used its interpretation of the observable pattern vis-e-vie their IObservable<T> and IObserver<T>interfaces (which I understand will be part of .NET 4 and hopefully SL4) and created so-called Observable Channels - which are basically singleton implementations of the IObservable<T> to which you can subscribe and publish. With the publish subscribe capabilities, it becomes a messaging framework kind of like Prism's EventBroker, but with a very easy to use API. 

MessagingFramework

As show above the Channel<T> class is the IObservable<T> implementation, to which any implementation of IObserver<T> can subscribe. Once subscribed, we return an IDisposable implementation based on the ChannelSubscriptionBase<T> class. In simpler terms you subscribe to a channel of Type T, whereby T can be any type you want to send and receive messages for, and on subscription you get a channel subscription token onto which you can call the Dispose method to get yourself unsubscribed.

Now, also provided is a generic IObserver<T> implementation predicatively called ChannelObserver<T>, and it makes it really easy to consume any channel's incoming data, as well Subscribe and Unsubscribe as required. Below is an example, for that:

   1: // declared
   2: ChannelObserver<ApplicationStateInfo> _observer;
   3:  
   4: // subscribe
   5: _observer = new ChannelObserver<ApplicationStateInfo>((s) => DoSomething(s.CurrentState));
   6: _observer.Subscribe(ThreadOption.UIThread);
   7:  
   8: // unsubscribe
   9: _observer.Unsubscribe();

Here we are tunning into the "ApplicationStateInfo" channel, which is one of the build in channel used by the Resource Locator Framework. It basically, publishes application lifetime state changes - which include starting, started, exiting, and exited states (this is based on IApplicationLifetimeAware callings). Note to subscribe one has to explicitly call for it, as shown in line 6, and the option we are excising there is to receive the subscription on the UI thread. Similarly to unsubscribe you need to call the Unsubscribe method and you can also check if you are currently subscribed via the IsSubscribed property. Further, once you have unsubscribed you can subscribe again, which makes it really easy to play/pause a subscription using the ChannelObserver.

By default, subscriptions are weakly referenced - which means that even if a subscriber that goes out-of-scope, were not to unsubscribe, it would still be available for GC (though you should always unsubscribe). On the flip side, if you wanted to ensure a non-weak referenced connection, for performance reasons or otherwise you could choose an option during subscription to keep the subscriber strongly-referenced.  Just as in Prism's Event Broker (whose API I've mimicked), you can subscribe to on the UI Thread, on the Publisher's Thread, or in a Background Thread. Also you have the option to publish asynchronously, however in this case you need to ensure the subscribers don't run into cross-threading exceptions. And keep in mind that, by design, a Channel always throw back any exception raised by a subscriber whilst receiving a payload.

Publishing to a channel is very straightforward, just use either the Channel or Channel<T> class to publish, there are also non-generic overloads available for publishing. Below is a straightforward example, of publishing a SearchQuery:

   1: // to publish a search query
   2: Channel.Publish<SearchQueryInfo>(new SearchQueryInfo("Silverlight"));
   3:  
   4: // to publish async search query
   5: Channel.PublishAsync<SearchQueryInfo>(new SearchQueryInfo("Silverlight"));

ChannelPublishActionAlso included is a trigger action which allows publishing to a channel directly from the UI. Because the ChannelPublishAction can bind the payload from the ViewModel, you could rig say a button 'click' to trigger the publishing. Also it can determine the channel by the type of payload set, however in cases it is expected to be null or based on derived types, you must set the ChannelType explicitly.

Coming back to the Rx Framework, because the channels are basically an IObservable implementation they are open to party on the IObservable-related LINQ operators available in the Rx Framework. And this is big deal, because you do a lot of intelligent processing on the client side (and I will try and show this separately with a post). However note, the current build doesn't take a dependency on the Rx Framework, but a separately compiled version is available if you require.

Resource Locator Framework

IResourceLocator The Resource Locator (RL) is basically a thread-safe register of resource locators, and a resource locator is an implementation of the IResourceLocator interface, which identifies any given resource by a unique name and can return an instance of that resource (see the interface on the right).

This really is not far off from IoC components, but the idea here is that any type of resource can register its own locator. And the locator's resource materialization strategy is its own business, and so when the RL is asked for a resource, it delegates to the locator. The core of this is really very simple, but around the resource registry are a number of utilities that really make it's consumption seamless and almost transparent from direct use. 

The RL is actually a generalization of what was there in the first drop of nRoute; in fact I had two separate implementations one for navigation and one for actions that did the same thing but in a more specific manner. If you have used nRoute you will know things like the MapNavigationContent, MapActionHandler attributes that when used with MapAssemblyRoutes or MapLoadedAssembliesActions static methods located all resources and fed them into the routing engine as routes. Here with the RL, we generalized that to not just produce routes (which themselves are actually locators in a way) but return IResourceLocator which is independent of any particular use.

Now the question is how do we feed locators into the RL registry, we could do it manually one by one, through a configuration file, or we could do using my preferred way by the means of an Assembly Mapper. The mapper basically looks for all MapResourceAttribute derivates in any given assembly, and yields an IResourceLocator implementation, which is then registered automatically.

Well, we have five feature implementations in the toolkit that make use of the RL, lets have a look at them individually.

Modules

The modules concept is straight out of Prism, but herein we use the RL with attribute-based mappings to locate and instantiate a module. For example:

   1: [MapModule("ContactsModule")]
   2: public class ContactsModule : IModule
   3: {
   4:     // .. implementation 
   5: }
 
Well, line 1 is all you need to have this module located and instantiated - we have also given the module a name by which you can locate it within the registry. The MapModule attribute takes two more parameters if you like, one an InitializationMode enumeration by which you can choose to have this instantiated when the application starts or alternatively as required. The other parameter is an optional array of strings declaring dependencies on other modules (by their names) - and the assembly mapper ensures that the module is not instantiated or registered until all the dependencies are resolved. 

Modules

Thanks to the RL, there is nothing much to the Modules concept, and the only important class is the IResourceLocator implementation which is registered into the RL by the MapModule attribute. And the ModuleLocator static class is just a candy wrapper around the ResourceLocator static class, but specifically geared for Modules-related info. Also by overriding the DefaultModulesLocator and MapModuleAttribute implementations you can add more features or change the internal workings to your requirements.

Services 

Again akin to Prism, services are essentially an implementation of some service contract (defined as an interface) which can then be located and realized.

   1: [MapService(typeof(IDateService))]
   2: public class DateService : IDateService
   3: {
   4:     // implementation of IDateService
   5: }

Here in Line 1, we are registering a Service of type IDateService which here is implemented by the DateService class - note the mapped class must implement that identified service contract. Now there are two more optional parameters to that attribute, which let you specify a name for the service, another one lets your list an array of other service types that the is dependent on. Also, you have three more named parameters, using which you can specify the lifetime of the service (see the InstanceLifetime Enum), initialization mode (see the InitializationMode Enum), and a boolean value specifying as to if it is the "default" service. Services

Like with the ModulesLocator static class, we also have a wrapper class for Services which helps with getting/checking for services. Also with services, actually with all types of resources, there is a concept of having a default resource - which is either a specifically designated resource (see the SetDefaultService<T> method above) or by default the first registered resource is considered the default service. So in the case of a default service, it can be retrieved without having to specify a name. So for example:

   1: // get the default service
   2: _dateTimeService1 = ServiceLocator.GetService<IDateTimeService>();
   3: // get a named service
   4: _dateTimeService2 = ServiceLocator.GetService<IDateTimeService>("GMT");

If you said this is just about like using any IoC component out there, well, I would agree with your - and feature-wise this implementation is not even that sophisticated. However the services as a concept has a lot of semantic value, which in this context is a non-visual building block for your application. Nonetheless if you wanted more smarts, you could "smartern" the locators up by creating a custom IResourceLocator implementation that uses an IoC component under the hood.

View Models

In the earlier release of nRoute we had this unfortunately named MapViewModelViewNavigation attribute, using which you could specify the View type, the ViewModel type and a Url to go with that - and what it did was when the Url was requested it instantiated the View in a Navigation Container, then create the ViewModel, which it injected into the View as its DataContext. Here with the toolkit, we don't have the composition capabilities of the nRoute Navigation component, but we have resource locators that can inject the ViewModel into a View using behaviours. Lets look at an example:

   1: [MapViewModel(typeof(Page4))]
   2: public class Page4ViewModel : ViewModelBase
   3: {
   4:     //..
   5: }
   6:  
   7: // OR - choose either way
   8:  
   9: [MapView(typeof(Page4ViewModel))]
  10: public class Page4 : UserControl
  11: {
  12:     //..
  13: }

BridgeViewModelBehaviorAbove we are defining the association between a View and a ViewModel, you could choose either of the two mapping mechanisms - either map the View and specify the ViewModel type or map the ViewModel and specify the View type. Once we have that all you need to do is drop the "BridgeViewModelBehavior" on the View's (at the root level).

This behaviour uses the RL to locate and instantiate a ViewModel instance and then injects it into the View's DataContext. Further, as you can see on the right, we can even bind some commands to the View's lifetime events - specifically for initialization, loading and unloading. Each command can pass in a parameter, and that too is bindable. Unfortunately, the unloading command was not firing so I've disabled it for now - it seems that the OnDetaching method on the behaviour is not being called.

We also a have specialized ViewModelLocator, if you like to use it procedurally.  ViewModelLocator

Also in the nRoute.ViewModels namespace you will also find a ViewModelBase class, which just implements the INotifyPropertyChanged interface and provides an helper to notify property changes. Note, its use is not required.

View Services

The idea of the ViewServices is that the ViewModel shouldn't have to take dependency on visually implemented controls or on platform specific contraptions - think notification balloons, save file dialog, etc. In practical terms, these are exposed just like services, where we have an interface defining the contact and an implementation that is transparent from its consumption. Now, build into the toolkit are four such services for opening files, saving files, showing messages and showing exceptions.
 ViewServicesContracts

To call upon any ViewService you can make use of the ViewServiceLocator static class, which just like the ServiceLocator requires the type of ViewService and optionally a name.

   1: IShowMessageViewService _messageBoxService;
   2:        
   3: // setup 
   4: _messageBoxService = ViewServiceLocator.GetViewService<IShowMessageViewService>();
   5: _messageBoxService.ButtonSetup = MessageBoxButton.OKCancel;
   6: _messageBoxService.Text = "Please confirm?";
   7:  
   8: // use 
   9: var _result = _messageBoxService.ShowMessage();

And similarly, declaring a ViewService is very much like everything else.

   1: [MapViewService(typeof(IShowMessageViewService), IsDefault=true)]
   2: public class NewShowMessageViewService
   3:    : IShowMessageViewService
   4: {
   5:     // IShowMessageViewService Implementation
   6: }

The MapViewService attribute requires that you specify the type of ViewService you implementing and optionally it can take in a name, you can also configure the lifetime and the initialization mode - very much like Services. Also you get a ViewSerivceLocator static class that helps you consume ViewServices.

ViewServices

Now, ViewServices are different from plain-jo services in two ways, one, it is semantically designated for View related functionality whereas ordinary Services, like with Prism, are more back-end providers. The second difference is a more practical one, you could define a ViewService directly within a UIElement or UserControl implementation - and this can then be the located by scanning the VisualTree. If you look at the ViewServiceLifetime enumeration, we have a DiscoveredInstance option which works by looking for the first instance of the ViewService in the VisualTree. Another, similar option is the SelfRegisteredInstance, wherein a UIElement or UserControl declares that it's a ViewService but will will self-register it's instance through the ViewServiceLocator when it is realized in the VisualTree.

In some ways if you look at Child Windows or MessageBox or File Dialogs they are like non-integrated visuals - they are not in the VisualTree per se, whereas if you have a status bar within the main UI  that can be called an integrated-visual. So the Discovered and Self-Registering instances option is to support these kind of integrated visuals, whose life-time you do not control directly, but yet they need to be addressable directly from some Service or ViewModel.

Consider, if we have a background-running "Stocks Watch Service" which finds-some abnormalities with your preferred stock, and it want to notify you - what does it do? Well, you could give it a ViewService contract, by which it can notify the user. This idea can be used further to componentized your visuals and avail them for without creating UI dependencies, so for example you could create a Bookmarks Panel ViewService, or Logged In/Logged Out controlling ViewService.

 Intergrated-Visual

I am not sure if this is very clear, but I will provide some samples showing how this can help to expose and consume visual components in a non-visual manner.

Channel Observers

Earlier I had shown an in-built IObserver<T> implementation, which really makes it easy to listen to any channel without having to implement the IObserver<T> interface; however in some cases you might want a dedicated listener - for example, a logging observer. In these cases you can implement the IObserver<T> interface onto a class and we can register and avail it though the RL. For that, we could do something like:

   1: [MapChannelObserver(typeof(ApplicationStateInfo), 
   2:     InitializationMode=InitializationMode.WhenAvaliable,
   3:     Lifetime=InstanceLifetime.Singleton)]
   4: public class ApplicationStateObserver : IObserver<ApplicationStateInfo>
   5: {
   6:     // IObserver<ApplicationStateInfo> Implementation
   7: }

Here we are mapping the ApplicationStateObserver class as an observer for the AppicationStateInfo Channel, we have set it to be realized as a singleton instance as soon as it is registered into the RL. Also when mapping you have the option to have it listen on a particular thread, see the ThredOption enumeration. Further, you can rely on the RL to instantiate the observer very early in the application lifetime, even before the RootVisual is created.  ChannelObservers.cs

And like before, we also have a static ChannelObserverLocator, using which you can locate your registered observers - though I am not sure how useful it is. Also, the IObserver<T> interface has three methods, the OnNext method is used to receive the channel payload, however the OnComplete is never called because a channel remains open for the lifetime of the application and I see no point executing the OnCompleted when the application is about existing. Lastly, the OnError method of the interface is also effectively not called because a Channel which implements the IObservable doesn't have the context of the publisher to generate an error - though I am mulling over the idea that any publisher can also publish an error. However, for now, just keep in mind that the workings of the channel-based messaging might change as my think evolves - and if you have any input on this, do share.

Locating Resources

One of the things with Resource Locator and it's preferred mechanism of using attributes to map resources, is that an assembly is the working currency - and indeed you could load an assembly and feed it to the AssemblyMapper static class to have any and all resources mapped. To aid this scenario, there is a RemoteResourceLoader class which helps you point to any url and load either a single dll or a xap file - in the later case it reads the xap's manifest and maps all included dlls. Here's how you can use it:

   1: // to load a dll
   2: var _loader1 = new RemoteResourceLoader();
   3: _loader1.AssemblyLoadComplete += Loader1_AssemblyLoadComplete;
   4: _loader1.LoadAssembly(new Uri("DynamicallyLoaded.dll", UriKind.Relative));
   5:  
   6: // to load a xap
   7: var _loader2 = new RemoteResourceLoader();
   8: _loader2.PackageLoadComplete += Loader2_PackageLoadComplete;
   9: _loader2.LoadPackage(new Uri("DynamicallyLoaded.xap", UriKind.Relative));

It really is very simple, and in the Assembly/Package LoadCompleted event you don't need to do anything to map the assemblies that is done for you once they are loaded, but if it was an error you will need to respond to it appropriately. Also the RemoteResourceLoader class has two static methods to check if any Uri is or has been used to load either a xap or dll.

In the attribute based mapping examples you have seen above, you have to tack the attribute on the mapped target - for example the MapModule attribute has to be tacked onto the IModule implementing type - however, this might not be possible sometimes or it may not gel with your preferences. So with toolkit there is another solution to this, a rather clean one, which allows you to "define", as oppose to "map", your resources. Have a look:

 AssemblyLevelDefines 

Here I created an empty cs fil, and added these assembly-level attributes - for all functional purposes, these attributes are the equivalent of the MapXX attributes described earlier. It works just as before, however when using the define version you need to specify the mapping target - for example with the DefineModule attribute you you have to specify the implementing type in addition to the name of the Module. Beyond the mater of personal tastes, the main benefit here is that rather than having mappings sprinkled all over the project, they located are in this one single location whilst still being strongly-typed. Also I hope the "Define" prefix as opposed to "Map" makes the intent clear here.

Quite obviously, the Resource Locator doesn't start by itself - you have to make it start and the recommended way to do that is to instantiate an nRouteApplicationService class into the Application's ApplicationLifetimeObjects collection.This can be simply done in your app.xaml file like this:

   1: <!-- declare the xml namespace -->
   2: xmlns:nRoute="clr-namespace:nRoute.ApplicationServices;assembly=nRoute.Toolkit"
   3:     
   4: <!-- and add it your application's LifetimeObjects collection -->
   5: <Application.ApplicationLifetimeObjects>
   6:     <nRoute:nRouteApplicationService />
   7: </Application.ApplicationLifetimeObjects>
 
This also happens to be the recommended way of creating "extension services" in Silverlight 3, plus it also helps to plug-into IApplicationService and IApplicationLifetimeAware related functionality. I've found this is easy to forget, but it is critical, so when there is a problem make sure your not tripping this.
 
Lastly, just as I have used the Resource Locator to created specific sets of locators you can do the same for custom locators - and it really is quite easy, just answer like six questions and you are in. I'm going to defer how to do to custom locators to a separate post, for which I have an example that shows how to dynamically collate "Search Providers" in a Silverlight app.
 
Break;
 
Because this post is already way-long, I'll have a part 2 which describes some of the other new features and what else is in store in the full-edition of nRoute. Also, please consider this as a pre-beta release, and I'll have a more polished release coming along with the full nRoute drop in a couple of weeks.
 
Download the toolkit from Codeplex.
 
Update: Part II is available here

Lately, its been raining M-V-VM (Model-View-ViewModel) in the SL and WPF world, and rightfully so because M-V-VM to me is the best pattern for application-development given the features in SL and WPF. Now, in this post I'm not going to introduce or detail the pattern itself, read this article by Josh Smith for a great intro, rather I'll go over what nRoute (download here) brings to the party as far as M-V-VM is concerned. And this is significant because nRoute was specifically, but not exclusively, designed for use with M-V-VM.

Separation of Concerns

From a larger perspective, M-V-VM is based on a simple principle of "separation of concerns" - in this case between the consumable View and the View's State and Behaviour which is represented by the ViewModel. However, it is important to appreciate that the ViewModel is not a dumb conductor, rather it is a contextually and state-fully rich orchestrator (which inturn makes the View as "logic-free" as possible). This separation also plays into enhancing the Developer-Designer workflow Microsoft has been touting for sometime.

Further, in my previous post about the demo app I explicitly tried to highlight how nRoute helps in another type of separation of concerns - between the infrastructure faculties and the actual actionable/usable content. Using Urls as a abstraction over content, nRoute dynamically binds together the infrastructure and content into a consumable application. The critical benefit being that infrastructure and the usable/actionable content can be clinically separated and evolved independently of each other.

This whole range of separation of concerns, with the traditional n-tier and domain-model helps create a flexible application and infrastructure - perhaps more complex, but one that will stand the stress-of-change much better.

Mediator

Central to nRoute is the routing engine, which is a direct port of the engine found in ASP.NET 3.5sp1 or MVC. It plays the role of a mediator that uniquely identifies resources using Urls, which are used for both composition and navigation purposes. In addition to a "resource locator" role the mediator also has another important role, which is that it allows for loosely-coupled dependencies amongst resources. When I say dependencies amongst, it can either be of composition nature like parent-child windows, or it can be of linkage nature like in wizards screens - both of which are discussed below. Also appreciate that because the mediator in nRoute uses string based Urls to resolve dependencies, your resources can evolve independently of each other akin to say HTML pages on a Web server.

Often people find the use of strings as locators a bit too loose of an abstraction, however Urls in nRoute are not magic-strings rather they have to be formally registered and properly formatted too. And equally the fact is that Urls are perhaps the most successful and all-encompassing form of resource locators in use. Further like MVC et al., Urls in nRoute support tokenised fragments which makes for even easier and broader use semantics.

Composition

Increasingly the metaphor of a "Window" is taking a back seat to the metaphor of a "Page", because with the success of the Web-Page model the window metaphor easily breakdowns in the face of web-like fluent user experiences. And though, it is not technically hard to achieve composition in its simplest form, what has historically hurt is the lack of a proper/built-in composition model. Further the complexity and clumsiness of solutions like Regions in Prism or WPF Frames hasn't helped, that is without even considering the locator, state-management, and navigation type issues the page metaphor brings.

And in this scenario, nRoute really shines because it brings a simple and well-understood model for composition using Urls, along with inherent support for state management and navigation features. The composition model in nRoute is akin to IFrames in HTML, and as suggested it makes use of so-called "container controls" (or simply containers) which by design exhibit different state-management behaviours (like Back-Forward History). Build into nRoute are four such container, plus the container model is fully customizable/extensible to accommodate custom needs. Now, what is profound here is that your content doesn't need to be aware of the container or vice-versa, because nRoute makes the composition magic happen without direct dependencies.

Further, like HTML pages/IFrames you can have one container within another, which allows for Master Pages or Parent-Child Pages type of use models. Alternatively, you can place two or more containers next to each other (each container individually addressable) to get something like the antiquated FRAMES model in HTML. In all, with the composition model in nRoute gives you a boat-load of flexibility coupled with a high degree of loose-coupling between the infrastructure and the content.

Navigation

With composition, navigation has always been the bane - but by using Urls it becomes both simple and easy to effect. Further, nRoute features an extensive range of behaviours that extend navigation to almost all control's common events, and accompanying that is a simple NavigationServices API. And depending on your preferences you can either drive the application-flow via code in the ViewModel or in the xaml based View. Additionally also supported is a concept-of an application-wide default container for navigation purposes, which comes into play in deep-linking scenarios.

State-Management

Interlinked to navigation is state-management, which in nRoute is an opt-in feature driven by a simple interface called ISupportNavigation. Within a M-V-VM archetype, you can implement the said interface in the ViewModel, and equally use it for both saving and restoring state independent of the View. Furthermore, the ISupportNavigation interface helps formalize the passing of tokenized parameters (and optionally a name-value collection) in the course of navigation. The benefit of state-management vis-a-vis navigation is that the lifetime of any View is limited to it being active in a container - however the content state can be persisted independent of the View.

Commands

Because of the nature of M-V-VM separation of concerns, the command-model gains added prominence in achieving the View and the ViewModel interaction pattern. And nRoute features first-rate support for both creating and consuming ICommands - it has an expansive implementation of non-routed Commands and behaviours to enable its consumption. The ICommand implementations which I blogged about earlier, features a strongly-typed parameter, INotifyPropertyChanged notifications, enabling/disabling the command, and a bindable command parameter property. Further, like in the case of navigation, nRoute features an exhaustive range of behaviours for consuming ICommands, which can respond to almost every control's common events.

Actions

Actions in nRoute are Url addressable functionality, that execute off the UI thread - this is useful for things like triggering some downloads or enabling pub-sub type of communications. The model for constructing actions is relatively simple, it is based on an interface called IActionHandler and the consumption pattern like earlier is based on attachable behaviours or alternatively by the use of the ActionServices API.  Further Actions support multi-casting to one or more globally registered handlers, and because of the loose-coupling it's a form of Weak Eventing using Urls. Also, you can direct an Action request to a specified handler which can be real handy sometimes, as described below.

In a way you can think of Actions in nRoute as mediated ICommands that can be addressed, in a loosely-coupled fashion, via Urls. And like ICommands, you can expose Actions in your ViewModel using a Delegate-Command type property (see the DelegateAction type), and on the View side you equally could bind to the Action property for use with behaviours. Further, like navigation Urls the actionable Urls also supports tokenized Url fragments and additively a request can be furnished with a name-value collection parameter for greater flexibility.

ViewModel Injection

One of the obvious to-dos with M-V-VM is injecting the ViewModel into the View - and because in nRoute the Views are instantiated by the mediator it gives us the perfect opportunity and place to inject the ViewModel. There is a build-in attribute-based approach to this, which uses the wordy MapViewModelViewNavigation attribute to set the ViewModel as the DataContext of the View. However, you are not constrained to use this attribute, you could easily create your own attribute-based implementation that say uses a service locator to determine and inject the ViewModel. Further, if you know MVC then you'll appreciate how much can be done by creating a custom IRouteHandler, and in nRoute using the IRouteHandler extension point you could totally lay out a custom M-V-VM implementation atop nRoute.

Service Locators

One of the common tripping points with M-V-VM is the use of platform specific and/or task specific functionality like MessageBox or File Dialogs in the ViewModel. The solution for the same is wrapping the functionality in a platform/task agnostic way into a locatable service; however this begins to creep mightily into the territory of Service Locators such as Unity or NInject, which makes me rather uncomfortable. So, I am considering having a set of M-V-VM helper services that optionally plug-into your chosen implementation of a Service Locator (reverse Dependency Injection?).

Forthcoming Additions

In addition to the helper Services, a number of forthcoming features in nRoute will directly help with M-V-VM. Firstly, as described in my earlier post, we'll have strongly-typed INotifyPropertyChanged support using extension methods. Also introduced will be bindable data-triggers for SL, which can be used to trigger either Navigation, ICommands or Actions. And probably something like an Action that yields a response, with the response being consumable in the View. 

In summary, I hope what is observable through the list of features mentioned above, is that nRoute is acutely geared towards realizing M-V-VM type of applications - ensuing a range of benefits probably described elsewhere.

Posted by Rishi on 13-May-09 7:44 AM, 30 Comments

Update: The ICommand implementation in this post was designed for Silverlight 2, for Silverlight 3 I've put out some new ideas in library called nRoute.Toolkit (download at Codeplex). Related to ICommand the toolkit contains:

- Two ICommand implementations including both generic and parameter-less versions
- ICommand extensions that allow you explicitly define execution-state dependencies (i.e. for CanExecute)
- A Blend based behaviour to use ICommands, that is both bindable to your ViewModel and can manage the state of the control it is applied to

Read full details about the above in my Introducing nRoute.Toolkit (Part 2) post.

The M-V-VM pattern (click here for M-V-VM intro) is perhaps the flavour of the season, it seems to be getting a lot of attention in the SL/WPF community. And rightfully so, because it goes very well with WPF/SL's databinding and data template feature sets. However, in Silverlight ICommand is there in name only, it's not inherently supported by the core-controls (which is a royal pain), but there are a number of reasonable workarounds till Silverlight 3 I suppose.

Anyway, just as a lot of developers I too created a non-event-routing based ICommand implementation for M-V-VM (specifically for SL but can equally be used for WPF). My implementation adds couple of things, let me enumerate:

  • It adds a CommandParameter Property; what this allows is to implicitly bind any UI based property to the parameter that is passed into ICommand's execution. So basically if you pass in a null in ICommand's Execute method it would substitute it with the CommandParameter's value.
  • Also, I've added an IsEnabled property, which is used to logically disable the command, as it "ands" the CanExecute result. I find this really useful, like say we are already executing a search and we don't want to get any more commands in, just say IsEnabled = false. This ties into the UI too, because changing it's value raises the CanExecuteChanged event.
  • Thirdly, the command class implements the INotifyPropertyChanged property, which goes with the two properties I've mentioned above. And like I said, when you disable the command or when the CommadParameter Property's value changes, it triggers the CanExecuteChanged event, that in turn ties into the UI.
  • I've also added a read-only bool property called IsExecutable, this again is mainly to bind to the UI as SL doesn't listen to the changes in CanExecuteChanged. So whenever CanExecuteChanged is raised we also raise IsExecutable's PropertyChanged event. This way you can say bind a button's IsEnabled Property to the IsExecutable Property, and it will automatically enable/disable the button. Notably, you can bind this to multiple UI element's, you are not limited to one UI element.
  • And because we get the value of the parameter for ICommand using the binding on CommandParameter Property we can just call Execute() or CanExecute() without passing in a parameter.

I am note sure if I got the benefits across, but essentially what this design helps is to better control the state of the command and it's consumption by the UI - particularly in Silverlight. Rather than having to expose two/three more properties, we can just use the command's properties notably with INotifyPropertyChanged Interface.

<TextBox Text="{Binding SearchCommand.CommandParameter, Mode=TwoWay}" />
<Button Content="Search" cal:Click.Command="{Binding SearchCommand}"
	IsEnabled="{Binding SearchCommand.IsExecutable, Mode=OneWay}" />

In the xaml above we bind the textbox's text property to the command's parameter value, and button is tied to the command. Also, I am using the Prism 2's attached properties for the click event consumption, you don't need one in WPF. And below is how you set up the command in the ViewModel.

_searchCommand = new ParameterCommand<string>(
    v => Search(v), v => !string.IsNullOrEmpty(v), string.Empty, true
);

public ParameterCommand<string> SearchCommand 
{
	get { return _searchCommand; }
}

void Search(string value)
{
    _searchCommand.IsEnabled = false;
    // do search.. 
    // show results 
    _searchCommand.IsEnabled = true;
}

For initializing the ICommand, I am passing in an execute handler, a canExecute lambda handler that checks the string is not empty, a empty string for the default value of the CommadParameter and true as in by default the command is enabled. When doing the search you disable the command and enable it back when done, and the UI part is handled with hook-ups shown earlier.

ParameterCommand

As for the structure, I have two base classes that are helpful when you don't wanna use the CommadParameter Property. The ActionCommand is mainly useful when you don't use a parameter, just an action like save or close. The delegate command is pretty much like Prism's but with IsEnabled rather than IsActive, however IsEnabled is tied in with INotifyPropertyChanged so it helps with UI consumption.  And the read-only IsExecutable Property checks both with the CanExecute method and IsEnabled property, and is also tied in with INotifyPropertyChanged.

Hope this helps, I'll have a running sample up soon, the complete code is below.

using System;
using System.Windows.Input;
using System.ComponentModel;

namespace Orkpad.Samples
{
    public class ActionCommand<T> : ICommand, INotifyPropertyChanged
    {

        protected const string ERROR_CANNOT_EXEC = "Cannot execute command {0}, invalid execution state or parameter.";
        protected const string ERROR_EXPECTED_TYPE = "Expected parameter for command ({0}) must be of {1} type.";

        Action<T> _executeHandler;
        bool _isEnabled;                 

        public ActionCommand(Action<T> executeHandler) : this(executeHandler, true) { }

        public ActionCommand(Action<T> executeHandler, bool isEnabled)
        {
            // basic check
            if (executeHandler == null) throw new ArgumentNullException("executeHandler");

            // we save
            _executeHandler = executeHandler;
            _isEnabled = isEnabled;

            // we also add an event handler which allows, anything binding to IsExecutable 
            //this.CanExecuteChanged += (s, e) => RaisePropertyChanged("IsExecutable");
        }

#region Additions

        //public virtual bool IsExecutable
        //{
        //    get
        //    {
        //        return IsEnabled;
        //    }
        //}

        public bool IsEnabled
        {
            get
            {
                return _isEnabled;
            }
            set
            {
                if (_isEnabled != value)
                {
                    _isEnabled = value;
                    RaiseCanExecuteChanged();
                    RaisePropertyChanged("IsEnabled");
                }
            }
        }

        public bool CanExecute(T parameter)
        {
            return OnCanExecute(parameter);
        }

        public void Execute(T parameter)
        {
            OnExecuteCommand(parameter);
        }

        public void RaiseCanExecuteChanged()
        {
            if (CanExecuteChanged != null) CanExecuteChanged(this, new EventArgs());
        }

#endregion

#region ICommand Members

        public event EventHandler CanExecuteChanged;

        public bool CanExecute(object parameter)
        {
            // basic checks
            CheckParameterType(parameter);

            return OnCanExecute((T)parameter);
        }

        public virtual void Execute(object parameter)
        {

            // basic checks
            CheckParameterType(parameter);

            OnExecuteCommand((T)parameter);
        }

#endregion

#region INotifyPropertyChanged Related

        public event PropertyChangedEventHandler PropertyChanged;

        protected void RaisePropertyChanged(string propertyName)
        {
            // basic check
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

#endregion

#region Internal

        protected virtual bool OnCanExecute(T value)
        {
            return IsEnabled; 
        }

        protected virtual void OnExecuteCommand(T parameter)
        {

			// I've changed this to not throw an exception, as failure to execute should fail gracefully
            if (!OnCanExecute(parameter)) return;
            //    throw new InvalidOperationException(string.Format(ERROR_CANNOT_EXEC, this.GetType().FullName));

            // we execute
           _executeHandler(parameter);

        }

        protected void CheckParameterType(Object parameter)
        {
            if (parameter == null) return;
            if (! typeof(T).IsAssignableFrom(parameter.GetType())) 
                throw new ArgumentException(string.Format(ERROR_EXPECTED_TYPE, this.GetType().FullName, typeof(T).FullName));
        }

#endregion

    }

    public class DelegateCommand<T> : ActionCommand<T>
    {

        Func<T, bool> _canExecuteHandler;

        public DelegateCommand(Action<T> executeHandler) : this(executeHandler, null, true) { }

        public DelegateCommand(Action<T> executeHandler, Func<T, bool> canExecuteHandler)
            : this(executeHandler, canExecuteHandler, true) { }

        public DelegateCommand(Action<T> executeHandler, Func<T, bool> canExecuteHandler, bool isEnabled)
            : base(executeHandler, isEnabled)
        {
            _canExecuteHandler = canExecuteHandler;
        }

        #region Helpers

        protected override bool OnCanExecute(T value)
        {

            // basic check
            CheckParameterType(value);

            // we execute, note the base checks 
            return (_canExecuteHandler != null) ? (base.OnCanExecute(value) && _canExecuteHandler(value)) : base.OnCanExecute(value);

        }

        #endregion

    }

     public class ParameterCommand<T> : DelegateCommand<T>
    {

#region Cosntants & Variables

        T _commandParameter;

#endregion

#region Constructors

        public ParameterCommand(Action<T> executeHandler) : this(executeHandler, null, default(T), true) { }

        public ParameterCommand(Action<T> executeHandler, T commandParameterDefaultValue) 
            : this(executeHandler, null, commandParameterDefaultValue, true) { }

        public ParameterCommand(Action<T> executeHandler, bool isEnabled)
            : this(executeHandler, null, default(T), isEnabled) { }

        public ParameterCommand(Action<T> executeHandler, Func<T, bool> canExecuteHandler)
            : this(executeHandler, canExecuteHandler, default(T), true) { }

        public ParameterCommand(Action<T> executeHandler, Func<T, bool> canExecuteHandler, bool isEnabled)
            : this(executeHandler, canExecuteHandler, default(T), isEnabled) { }

        public ParameterCommand(Action<T> executeHandler, Func<T, bool> canExecuteHandler, 
            T commandParameterDefaultValue, bool isEnabled) : base(executeHandler, canExecuteHandler, isEnabled)
        {

            // we save
            _commandParameter = commandParameterDefaultValue;

            // we also add an event handler which allows, anything binding to IsExecutable 
            this.CanExecuteChanged += (s, e) => RaisePropertyChanged("IsExecutable");

        }

#endregion

#region Additions

        public bool IsExecutable
        {
            get
            {
                // we check this here, because we can validate against the command parameter
                return this.CanExecute();
            }
        }

        public T CommandParameter
        {
            get
            {
                return _commandParameter;
            }
            set
            {
                if (!Object.Equals(_commandParameter, value))
                {
                    _commandParameter = value;
                    RaisePropertyChanged("CommandParameter");
                    RaiseCanExecuteChanged();
                }
            }
        }

        public bool CanExecute()
        {
            return OnCanExecute(this.CommandParameter);
        }

        public void Execute()
        {
            this.Execute(this.CommandParameter);
        }

#endregion

#region Helpers

        protected override void OnExecuteCommand(T parameter)
        {

            // we subsitute the 
            T _value = parameter != null ? parameter : this.CommandParameter;
            
            // we execute
            base.OnExecuteCommand(_value);

        }

#endregion

    }

}

UPDATE: I've got revised versions of all the three classes in nRoute, please visit http://nRoute.codeplex.com for the latest release and check out the demo app for examples on how to use these ICommand implementations.