As promised, I have updated the Prism Quick Start Kit and added a WPF quick-start solution and WPF project templates. You can download the latest release here. In the zip you’ll find four project templates (Shell and Module templates for WPF and Silverlight) and two quick-start solutions, one each for WPF and Silverlight.
To install the templates, copy the project template zip files to your Visual Studio C# template folder. On my system the templates go here:
“My Documents\Visual Studio 2008\Templates\ProjectTemplates\Visual C#”
You should also remove the previous Prism templates if you have installed them. Next, register the templates with Visual Studio by running
devenv.exe /installvstemplates
in a Visual Studio command prompt window (as admin).
When you run Visual Studio and create a new project, you should see the four templates show up in the Visual C# node.
Using the Prism project templates should be pretty straightforward. Couple of things to note though:
- When you create a project with any of these templates you should first of all update the references to point to the Prism assemblies on your system. The quick-start solutions come complete with a Lib folder that contains pre-built Prism binaries so they work out of the box for convenience, but you should try and use the Prism binaries on your system where you can.
- You will of course need the Silverlight Visual Studio tools to be installed before you can use any of the Silverlight project templates or the quick-start solution. See here for more information on getting started with Silverlight development.
- The WPF shell project comes complete with a module catalog that looks for modules in the local output folder. If you add a WPF module to your project you will have to copy the output module assembly to the shell’s bin/Debug or bin/Release folder. I use a post-build step on each module project to automatically copy the assemblies over after every build:
You’ll need to update this with the name of your shell project. You can achieve the same thing by simply adding project reference to your modules projects and then Visual Studio will copy over the assemblies for you, but since Prism advocates a loosely-coupled composite architecture this seems like cheating to me :-).
The Silverlight and WPF quick-start solutions are essentially the same – the only difference between the two is that the WPF shell includes a menu-like button that’s hooked up the shell’s Exit command. I also updated the quick-start solutions to include a style that can be applied to ContentControl regions so that a banner containing the region name is displayed. This is just to make it easier for folks to see where each region is located within the shell.

The quick-start solutions are meant to provide a skeletal solution on which you can build real application. They are not very interesting as a standalone app, but if you’re curious to see what it looks like you can run the Silverlight version of the quick-start solution here.
David Platt of Rolling Thunder has just announced another 3 day Prism training course to be held July 7th-9th. You can find all of the details here. It’s web delivered so you don’t even have to travel!
It looks like it covers a lot of material – there’s a detailed syllabus here – from the basic goals and architecture of Prism, all the way through to advanced scenarios with modules, services, loosely-coupled events, and UI composition.
If you’re looking to use Prism to increase the quality of your WPF & Silverlight applications and to speed up your development it’s definitely worth checking it out.
Building applications from scratch starting from a blank page or screen in Visual Studio is a frustrating, time consuming and intimidating task. Instead, most developers like to start with a working application that they can modify, tweak and extend to suit their needs.
Far too often though, developers take a demo or a sample as the starting point for their application, and this often leads to a poor application design that’s complex, difficult to test and debug, and inflexible. Demos and samples have their place of course – they are great for illustrating a single concept or a cool new feature – but they are typically not designed to provide a solid base for an entire application.
Prism is a library of design patterns that work together to provide a solid architectural foundation on which you can build real-world Silverlight and WPF applications that are flexible and maintainable. Some of the patterns that Prism contains are fairly simple while others are more complex, but they are designed to work together to solve some of the challenges you face when building these real-world applications.
We illustrate individual patterns using what we call ‘Quick-Starts’ which are small focused sample applications. We illustrate how the patterns work together using what we call a ‘Reference Implementation’, which is a large sample application that implements a real-world scenario (during development, we actually use the RI to help us figure out what challenges a developer faces when building a non-trivial real-world application, and from those challenges we distil the patterns that help to address them and then implement those patterns in a reusable library). For Prism, the RI is a Stock Trader application that allows you buy and sell stocks and to manage your portfolio.
However, neither the Quick-Starts nor the Reference Implementation that we include in Prism are great for taking as a starting point for a new Prism application. The Quick-Starts are too fine-grained and focused on one specific pattern or technique, while the Reference Implementation is too coarse-grained and includes a lot of application logic that’s specific to the stock trader scenario.
The Prism Quick Start Kit
To help with this problem, we are considering building a number of solution and project templates for Visual Studio that would give you a simple working app that you could tweak and modify. These would fall somewhere in-between the Quick-Starts and Reference Implementation and provide a basic solution and project structure into which you could add your application specific files.
I spent a couple of days this week prototyping this approach. I built a couple of project templates (one for a Prism Shell, and one for a Prism Module) and a solution template that provide a complete multi-module working app. You can download these templates from here. Together, these templates make up what I call the ‘Prism Quick Start Kit’.
Installation
Installation of the project templates is fairly straightforward:
- Unzip the starter kit and copy the ‘Prism Shell.zip’ and ‘Prism Module.zip’ files into your Visual Studio templates folder. They are C# templates so they go here on my system:
My Documents\Visual Studio 2008\Templates\ProjectTemplates\Visual C#
- To get Visual Studio to display the new project templates in the New Projects dialog, run the following command (as admin) in a Visual Studio Command Prompt window:
devenv.exe /installvstemplates
Getting Started With The Prism Project Templates
To see the project templates in action, follow these steps:
- Fire up Visual Studio, and click File/New/Web Site. Click on ASP.NET Web Site and enter ‘PrismApp’ as the folder name. This will create the web project that will host our Prism application.
- Next, right click on the PrismApp solution and selected Add/New Project. Select the ‘Visual C#’ project types node and you should see the Prism Shell and Prism Module templates in the My Templates section:
- Click on the Prism Shell template and then click on OK. This will create a Prism Shell project called ‘Prism.Shell1’.
- We need to tidy up the project references to point to the Prism and Unity assemblies. If you click on the References node you’ll probably see that these references need updating. If you’ve added these assemblies into your GAC then they should be ok, but if not, you’ll need to remove them and add them again by browsing to wherever you complied them on your system.
- Next, we need to link the Prism Shell project to the Web project. Right click on the web project and select Property Pages. Click on the Silverlight Applications node and then click the Add button. In the dialog, select the Prism Shell project and click Add then OK.
- This will link the Prism Shell project to the web project and create a test page. Right click on the Prism.Shell1TestPage.html page and select Set As Start Page. Press F5 and click Ok to enable debugging. You should see the Prism shell in all its glory:
- The shell includes all of the basic things you typically need in a shell – a shell View and ViewModel, a bootstrapper and a module catalog. The shell’s UI includes a simple 3 region layout. [Eventually, you can imagine having a whole gallery of different shell layouts and themes to choose from…]
- The next step is to create a Prism module project. Right click on the PrismApp solution, select Add/New Project, choose the Prism Module project template and click OK. This will create a module project called ‘Prism.Module1’. The project template contains all of the basic things you need in a module – a View and ViewModel, a basic data model and a data service.
- We need to do the dance with the references as above. [We’ll hopefully figure out a way to make this experience much better in the future…]
- Next, link the module project with the web project as above, but this time make sure that the ‘Add a test page’ check box is unchecked – we don’t need a test page for the module. Click Add then OK. This step ensures that the module’s xap file gets copied to the web ClientBin folder.
- The last step is to add the module to the shell’s module catalog. Open the ModuleCatalog.xaml file and uncomment the first entry:
<prism:ModuleInfo Ref="Prism.Module1.xap"
ModuleName="Module1"
ModuleType="Prism.Module1.ModuleInit, Prism.Module1, Version=1.0.0.0"
InitializationMode="WhenAvailable"/>
If you used a different name for the module, you’ll have to edit this to use the names that you chose.
- When you press F5, you will see the module get loaded into the shell and the module’s view displayed in the shell’s main region. You’ll also notice that the module includes a simple data model that gives the UI something to display. You can take this as a starting point and modify to suit your needs.

The Prism Quick Start Solution
I find the project templates described above pretty useful for creating new Prism projects, but there are way too many steps involved to make it a simple and clean experience. What I’d really like to do is to create a ‘Solution Template’ that includes all of the sub-projects and references all linked up and ready to go.
Unfortunately Visual Studio doesn’t by itself allow this to be done easily. There are additional tools and frameworks available that enable this, but at this stage I wanted to keep it simple so the next best thing was to just create a baseline sample project that I can manually copy and modify whenever I want to build a Prism multi-module solution. I call this the ‘Prism Quick-Start Solution’.
The baseline quick-start solution is the third zip file in the Prism quick-start kit. If you unzip it you’ll see that it contains Web and Shell projects, two Module projects and a ‘Common’ class library. The solution has all of these linked together and includes the Prism and Unity assembly so that you don’t have to fix up any references. In other words, you can unzip it and go!
If you run the app or examine the code, you’ll see that it contains a little more functionality than you get by just using the project templates described above. This is because, in a typical Prism application, there are a couple of common things that you need to do to coordinate the functionality between the Shell and the multiple Modules.
An example of this is when you implement loosely-coupled events between modules to coordinate context or user actions. The quick-start solution shows how to implement simple cross-module master-detail functionality – when you click on the Master View (from Module 1), the Catalog View (from Module 2) will update. This also shows how you typically coordinate data and context across two modules…
Another example is the use of a Controller class to programmatically coordinate the display of Views in a region in order to implement navigation or application workflow. The quick-start solution uses a controller class to programmatically display views in the main region when the user clicks on buttons in the master view.
The quick-start solution is meant to provide a basic structure for a Prism app and to include the most commonly used features of Prism. I find it very useful as a starting point because it contains all of the little code snippets and that you often need and has a basic structure in place making it pretty straightforward to take it and modify it to create many different types of applications. It’s hopefully also a good place to experiment with Prism and to learn about some of its basic features.
oO------Oo
I hope you find these templates useful. We’re hoping to provide templates like these in Prism 3.0 but we’d also like to provide item templates, code snippets and some simple in-tool automation to make building Prism apps really simple and straightforward. Let me know what you think, and whatever else you’d like to see in Prism 3.0…
Download the Prism Quick Start Kit here.
In my last post – Silverlight Navigation Part 3 – I outlined a mechanism whereby you could navigate to a View and have the application create and wire up the associated ViewModel automatically. I also showed the inverse of this, where you could navigate to a ViewModel and have the application automatically create and wire up the associated View automatically.
Whether you prefer the View-First or the ViewModel-First approach, the essential feature that really supports the ViewModel pattern is that the system should be able to create a ViewModel for a View (or vice versa) automatically. Otherwise, the burden falls to the developer to do this in code, which can result in a complicated architecture that’s either inflexible or difficult to understand and maintain.
Let’s say, for example, that you have adopted a View-First approach. Now, you could just have some code in your application (say, in a controller component or event handler somewhere) that simply creates the required View and it’s associated ViewModel and wires them together like this:
public ShowCustomer()
{
CustomerView view = new CustomerView();
CustomerViewModel viewModel = new CustomerViewModel();
view.DataContext = viewModel;
myContentControl.Content = view;
}
You can use this approach with a ViewModel-First approach too. Another simple approach is to just get the View to create its own ViewModel, either in its constructor:
public partial class CustomerView : UserControl
{
public CustomerView()
{
InitializeComponent();
this.DataContext = new CustomerViewModel();
}
}
or via XAML:
<UserControl.DataContext>
<CustomerViewModel />
</UserControl.DataContext>
All three of these approaches work great, except that they hard code your application to use specific View and ViewModel types. This may very well not be an issue for you, and if it isn’t, I say go for it!
However, there are times when you’ll want to have the View and the ViewModel types more loosely coupled. An example might be when you want to decide at run-time which View to display for a particular ViewModel based on, say, the user’s role, chosen UI theme, screen size, or even the type of device that the user is using(!). So, while the approaches above are simple, they are relatively inflexible.
Dependency Injection To The Rescue?
It is at this point that the Dependency Injection folks will start to gesticulate wildly and remind us that this is exactly the situation in which DI excels. Remember that with DI, if you have a dependency between one class and another, the system (i.e. the DI container) can automatically fulfill that dependency dynamically at run-time for you. This allows the classes to be more loosely coupled and removes the need for you to manage the creation of dependent classes yourself. Let’s see how this works…
Say we have a class ‘A’ that depends on (i.e. has a reference to) a class ‘B’. Typical DI containers (including Unity) require that we express the dependency between A and B using a type – typically (but not necessarily) an intermediate interface type, say IB – and that we define a constructor on A that takes a reference to that type. We then register our implementation of the intermediate interface type with the container – so that it knows that whenever anybody wants an implementation of IB it will create an instance of B.
So, when we want an instance of class A, we just ask the container to create one for us. It spots that class A requires a reference to an IB implementation, so it goes and creates a B for us automatically and passes a reference to it to A’s constructor. The container manages the creation of dependent classes for us!
It is of course true that in many situations DI is a good solution for this kind of problem. I think though, that for the ViewModel scenario DI is not ideal. To illustrate why, let’s see how DI typically works in View-First and ViewModel-First scenarios…
The Perils of IViewModel
In our View-First example above, we have a View that wants a reference to (depends on) a ViewModel, so we’d first register an implementation of our ViewModel with the container:
_container.RegisterType<ICustomerViewModel, CustomerViewModel>();
and we’d design the View so that it gets a reference to the ViewModel implementation in its constructor:
public CustomerView( ICustomerViewModel viewModel )
{
this.DataContex = viewModel;
}
Finally, we’d get the container to create an instance of the View. The container will automatically create an instance of the registered ViewModel type and pass a reference to it into the View’s constructor.
CustomerView view = _container.Resolve<CustomerView>();
Ok this works, but I think there are a number of problems with this approach:
- To create the View we have to use the DI container. We can’t just create the View using ‘new’ and we can’t create it declaratively via XAML (since that will use the default constructor which won’t pass in a reference to the required ViewModel). In other words, we have to have a controller or event handler or some code somewhere that creates the View via the container by calling Resolve.
- The UI designer (even if the UI designer is really a developer) should not have to write code in the View just to make it work. If there is some complicated UI behavior that can’t be done declaratively, then code may be required, but this should be a special case and not required every time just to get stuff wired up and working. Even implementing the simple constructor above takes some explanation and can be easily forgotten or incorrectly implemented.
- We have defined a ‘marker’ interface type that we don’t really need – i.e. the interface has no properties or methods, we’re just using it as a marker. Yes, we could define some properties and method on it, but the View should not be programmatically calling into the ViewModel. Remember, UI designers should not have to write any code. All interactions between View and ViewModel should be done via bindings and attached behaviors so that the View is just a loosely coupled observer of the ViewModel.
The Evils of IView
So that’s Dependency Injection in a View-First world. What about a ViewModel-First world? Well, things are no better here either. Similar to the process outlined above, we’d probably define an IView interface; register an implementation of it with the container; define a constructor on the ViewModel that accepts an IView reference; then create an instance of the ViewModel using the container:
_container.RegisterType<ICustomerView, CustomerView>();
...
public CustomerViewModel( ICustomerView view )
{
((FrameworkElement)view).DataContext = this;
}
...
CustomerViewModel viewModel = _container.Resolve<CustomerViewModel>();
Again, a couple of problems with this approach:
- Again, we can’t create a View declaratively using XAML – the container will create the View as a result of creating an instance of the ViewModel class – so we’d have to have a controller or event handler or some code somewhere to kick things off.
- We’d have a marker interface that we’d don’t really need and that won’t define any properties or methods – the ViewModel should not be programmatically calling into a View.
- The UI designer would have to implement an interface on the View each and every time they create one. It’s not terribly complicated, but the UI designer should not be required to write any code except for advanced scenarios.
- The ViewModel-First approach is actually slightly worse that the View-First approach because of the nasty cast in the constructor. This is required in order to set the view’s data context to the ViewModel.
Wouldn’t It Be Nice If…
In my last post on navigation, I showed a couple of different approaches to the problem of conjuring up a View for a ViewModel (or vice versa) without using a Dependency Injection approach.
- For View-First, instead of using DI and defining interfaces and constructors, I just used an attached property on the View to specify the type name of the ViewModel (ViewModel.TypeName) and the system automatically constructed the ViewModel for me and wired it up to the View’s DataContext.
- Going the other way (ViewModel-First) , I just used a naming convention to infer the name of the View from the ViewModel’s type name, created an instance of that View and set it’s DataContext.
Neither of these approaches are ideal though, so I got to thinking what an ideal approach might look like… The key is that we need a simple way of expressing the relationship between the View and the ViewModel types so that the system can just make the right things happen!
If you’re familiar with DataTemplates in WPF, you know that it’s possible to define a DataTemplate (somewhere in the application’s resources) for a particular (non UI) type. Whenever the system has to display an object of that type, the DataTemplate is automatically used to visually represent it. Under the covers, the system creates an instance of the DataTemplate, sets its DataContext to the object that it represents, and then displays it in the UI. Silverlight does not yet support implicit data templating – you have to specify the DataTemplate explicitly for each control – but the mechanism is very similar.
I think this is close to what we want…
I think of DataTemplates simply as “Thin Views” – i.e. purely declarative Views with no code behind. They are very useful, but sometimes you just need to have some code in the View (for complex visual behavior that can’t be done declaratively). So, if the system could be extended to include Views that could have code behind, it would all fit together in a nice, simple, consistent model. It could look something like this…
We define a View as usual and simply declare that it is associated with a ViewModel data type:
<UserControl x:Class="MySample.CustomerView"
DataType="{x:Type MySample.CustomerViewModel}"
For the ViewModel-First approach, we simple create (or navigate to) an instance of the ViewModel and display it. For example,
MyContentControl.Content = new CustomerViewModel();
The system would then step in and create an instance of the View that corresponds to this type and would wire up the DataContext for us – just like the system does today with DataTemplates!!!
Similarly, for View-First, where we simply create (or navigate to) a View, the system would automatically create an instance of the associated ViewModel type for us and wire up the DataContext. There would likely be another property to control this behavior.
I think this approach has a number of benefits:
- The system carries the burden of finding and creating corresponding Views and ViewModels, making our application code much, much simpler. And simpler means that it’s faster to write, easier to debug, and easier to unit test!
- It gives us a single consistent model that works for Views with and without code behind.
- It works declaratively as well as programmatically giving us a lot of freedom to create Views or ViewModels in code or in XAML as desired. It works great with navigation too.
- It allows Views to express a dependency on a particular ViewModel, while allowing ViewModels to remain completely View agnostic. This opens up a whole host of interesting design-time tooling possibilities – like you get with DataTemplates today – but with more explicit support for the ViewModel pattern. For example, you can imagine that the UI designers can provide intelli-sense or drag & drop support for binding expressions and behaviors (because the design-time system can determine the ViewModel’s commands, notifications and properties).
You’ll have noticed that we’re not using an intermediate interface type to loosely couple the View and ViewModel. The approach could be extended to support that though, for example by using the upcoming Managed Extensibility Framework (MEF), or by building in some form of simple Dependency Injection mechanism into the XAML loader system.
Until I prototype this approach more fully, it’s not clear whether it will really work as well as expected. Also, it’s not clear at this stage when (or if) we could expect it this approach to be implemented in the platform.
We can but dream though…
Welcome to the third post in my series on navigation in Silverlight! The goal of this series of posts is to provide a simple to use framework (called Helix) for building Silverlight applications that are based on a flexible navigation mechanism and the ViewModel separated presentation pattern. This post is long and was a tough one to write (which is partly why it took so long to complete!) but this post takes us much closer to our goal.
If you’ve been reading this series from the beginning, you’ll have noticed that we’re taking something of an agile approach to building Helix. You can think of each post in this series as an iteration. And like all good agile projects, we’re not afraid of a bit of refactoring, or of adding or significantly altering features as we tackle new scenarios. So in the latest version of Helix you’ll find some changes compared the version in part 2.
Some of these changes are bug fixes, but most are new features or extensions to existing features to support the ViewModel pattern alongside navigation. You’ll also find more samples and unit tests in this drop. There is a summary of the main changes and new features at the end of this post. You can download the latest release from here and you can run all of the latest samples from here.
The Story So Far…
Before we get into any details, let’s quickly review what we’ve covered in previous posts…
In the first post in the series, I introduced the Helix Frame and NavigationLink controls and showed how they could be used together with a simple Journal to implement a simple navigation mechanism between pages in a Silverlight 2.0 application.
In the second post in the series, I introduced the Route, NavigationHandler and NavigationController classes and demonstrated how they can be used to implement navigation between pages based on parameterized navigation links. That post also showed two ways of passing parameters via the navigation link to the target page, so that the page can be initialized or have it's context set appropriately.
One way was to use the NavigationPageController class which passes all of the navigation parameters to the target page's OnNavigate method (through the INavigationPage interface). The other way was to use the PageActionController class which invokes a page action method on the target page by mapping the navigation parameters to the method's name and it's parameters.
Both of these approaches created an instance of the target page and then passed the navigation parameters directly to it. As noted in the second post, this is clearly not ideal since it means that the page will then contain application logic as well as UI – not good for a lot of reasons!!!
Separated presentation patterns like the ViewModel pattern help to keep the UI and application logic cleanly separated. I described the ViewModel pattern in a previous post, but to recap, the ViewModel pattern separates UI and presentation logic into View and ViewModel classes, and uses data binding and commands to communicate between them. In this post, I provided an implementation of a generic ViewModel for handling collections, imaginatively called CollectionViewModel. In this post, I described two strategies in which the View and the ViewModel can get created and linked up. In View-First composition, the view is logically created first. In Presenter-First composition, the presenter (the ViewModel is our case) is logically created first.
These three additional posts can be considered parts 2a, 2b and 2c of this series, so please check them out if you haven't already done so. We’ll be building on the concepts and features they describe in this post.
Ok, that’s the background information out of the way. Let’s get started extending the Helix navigation framework so that it works alongside the ViewModel separated presentation pattern…
The Challenge: Mixing ViewModels and Navigation
One of the challenges with any separated presentation pattern is that you have to have some way of creating, hooking up and managing the additional components that are involved. In our preferred ViewModel pattern these additional components are principally Views, ViewModels and Models.
Now, if your application is fairly static, it’s fairly straightforward to create and hook up these components. But if your application is more dynamic (for example, when the UI changes constantly because the user is navigating around within the application!) then things are not quite so simple. As well as creating and hooking up these components during navigation, we also have to figure out how the other parts of the application are going to interact and communicate with them.
In my experience, this issue – the handling of Views, ViewModels and Models in a dynamic application that includes navigation – is the one that causes the most confusion and pain for folks building real-world applications using the ViewModel pattern. It is this very issue that we’re going to tackle in this post…
Choosing A Navigation Scheme
Before we get into the details on the integration of the ViewModel pattern into the Helix navigation framework, we first have to think about the different ways in which we can structure our application so we can and navigate around within it.
Helix essentially allows you to design a navigation scheme for your application by allowing you to decide how the various elements in your application are linked together by parameterized Uri's. When you define the format of the navigation links in your application, you are designing the way in which the user will navigate through your application to access its functionality and content by identifying the main navigational elements in your application and identifying which parameters are passed to them. At a high level, there are two basic navigation schemes to choose from.
Perhaps the simplest navigation scheme is one where the application's navigational links refer directly to the application's visual elements. Using this scheme means that we'll link the application together using Uri's that refer to pages or controls within the application and allow the user to navigate between them. This is the navigation scheme that we used in the last two posts of the series. I think this type of navigation scheme tends to work great for content-centric applications – i.e. when the user expects to be primarily navigating through content. Blog readers, news readers, and media sharing apps are good examples of this type of application.
With Helix you are not limited to using simple page-based navigation schemes. You can link your application together in other interesting ways. In particular, you can structure your application so that it's composed of tasks or actions that the user carries out. I call these types of applications task-centric applications.
Let's look at a simple example – an expense reporting application. In terms of tasks, the user can create, edit, submit, approve, reject, or archive expense reports, so we could structure our application so that the user naturally navigates between these tasks in sequences that are natural. For example, the user may start by creating a new expense report and then submit it for approval; then they may edit a draft expense report and save it for later submission; then they may review their approved expense reports and archive them away for safe keeping.
I think this type of navigation scheme is very interesting. It means for instance, that we can align our application’s navigational structure with the application's use-cases and the user’s tasks, rather than having to strictly follow the visual structure of the application. This means that we can more cleanly separate the visual structure of the application from its logical structure and work flow, which in turn means that we can more easily test the application, and have more flexibility when designing a fluid, animated UI for it. In addition, when we consider deep linking (in a future post) we'll see that the user, or other systems, very often will be exposed to the navigational structure of the application, so having a navigation scheme that’s independent of the visual structure can also be important for many other reasons.
At this point you might be asking: “Yes, but does it really matter what the navigational scheme for an application is since the user never sees it – they just click on links and the UI gets updated?”. This is of course true, up to a point. It’s not clear that one approach is superior to the other – I can see advantages and disadvantages with each – so we’ll explore both approaches to see what each feels like when building an application.
Whatever your choice of navigation scheme, content-centric or task-centric, the important thing is that you are comfortable with it and use it consistently throughout your application. Using multiple schemes within the same application can lead to user confusion and an application that’s difficult to maintain or extend. Choosing a navigational scheme that's natural for your application will help you build, test and extend it much more easily and will help to make it easier to use, so it’s important to design your navigation scheme wisely and to stick to it.
Ah, But What About The ViewModel?
Regardless of the navigation scheme, things get even more interesting when we introduce the ViewModels pattern into the navigational picture. Using the ViewModel pattern means that we'll have a component that encapsulates the UI (the View), and a component that encapsulates the presentation logic and state (the ViewModel). My post here describes the ViewModel pattern in some detail.
The View and the ViewModel have to get created and hooked up together and this can happen in one of two ways – the view is either logically created first followed by the ViewModel on which is depends, or the ViewModel is logically created first followed by the View on which it depends. I call these two mechanisms View-First or ViewModel-First composition respectively – see my post here for more details.
Now – and this is a key point – if you think about a content-centric navigation scheme as described above, you'll see that this maps very naturally to View-First composition! The user is logically navigating to a View so we construct the View first, followed by the ViewModel on which it depends and that provides a clean separation between UI and presentation logic.
On the other hand, with a task-centric navigation scheme, the user is logically navigating to a component that manages an activity or task. This component (as we'll see below) maps quite naturally to a ViewModel, so logically we're creating the ViewModel first, followed by the View on which it depends so that it can be visually represented in the UI. In other words, task-centric navigation maps naturally to ViewModel-First composition!
So, we can clearly identify two distinct navigational styles:
- View-First Navigation – Where the user navigates between Views in a content-centric application,
- ViewModel-First Navigation – Where the user navigates between ViewModels that represent tasks or activities within the application.
Interestingly, you can also see the correlation between
content-centric navigation and view-first composition, and
task-centric navigation and presenter-first composition, in ASP.NET web applications.
With traditional ASP.NET web applications, the application consists of a number of pages that are linked together by simple Uri's. In other words, the navigational structure of the application is based on visual elements linked together. With ASP.NET WebForms, the pages can be richly defined using server-side controls, client-side AJAX controls, and with MasterPages and so on, but the navigational structure is always based on pages and the ASP.NET runtime will create the pages as you navigate to them. You may optionally choose to separate the presentation or business logic from the UI by using an MVP pattern, but in this case, the Presenter will be constructed by the page itself.
On the other hand, using ASP.NET's MVC framework, we can define a navigational scheme that follows the logical structure of our application and that is independent of the visual pages within the application. By defining suitable navigation routes we will logically navigate to a controller component which then allows us to create a suitable view and hook it up to a data model component. We technically have controller-first composition, but hopefully you can see that this is the moral equivalent of constructing a ViewModel before the View.
In this latest drop of Helix, I’ve added support for both View-First navigation and ViewModel-First navigation by implementing a navigation controller for each. The rest of the Helix architecture remains essentially the same (though there are some new features and some fixes as detailed at the end of this post). Remember, you can always implement a custom controller if you want to change the implementation that’s described below.
Instead of walking through the implementation of these controllers, it’s probably more useful to walk through a sample application for each navigation style so you can see how they are both put together. In the examples below, I’m also using some of the new and improved features in Helix that are common to both styles of navigation.
Ok, enough theory, let’s see some code!
View-First Navigation
To illustrate View-First Navigation, I took the Order Entry sample application from the second post and converted it to use ViewModel pattern. You’ll remember that this sample was based on a navigation scheme where the links referred to the pages within the application, so it was relatively straightforward to keep that navigation scheme and introduce the ViewModel pattern into it. You can run the final application here. Let’s walk through the application so you can see how it all fits together…
The application consists of a number of Models, ViewModels and Views, plus a RootPage and an Application class. The RootPage is a simple page with a Frame control – as we navigate between pages, they will displayed here.
The application uses three model classes to represent the customer, sales order and the sales order line items. In this sample these are just simple classes with a number of properties. These are all defined in the Models folder.
The ViewModels for the application are defined in the ViewModels folder. The ViewModels implement a number of commands and properties that the Views can bind to. The application’s pages are all defined in the Views folder. None of the pages have any code behind; all of the UI is defined declaratively in XAML. The pages bind against the ViewModel’s commands and properties.
All of these classes are connected together at run-time through navigation. The navigation scheme for the application is defined in App.xaml. With the latest drop of Helix, we can define the navigation routes, and associated controller and default parameter values, as an application resource. This allows us to define the navigation scheme for our application declaratively without having to write any code.
<n:RouteTable x:Key="GlobalNavigationRoutes">
<n:Route UriTemplate="/[PageName]">
<n:Route.Controller>
<c:PageController DefaultResourcePath="Views" />
</n:Route.Controller>
</n:Route>
<n:Route UriTemplate="/[PageName]/[CustomerID]">
<n:Route.Controller>
<c:PageController DefaultResourcePath="Views" />
</n:Route.Controller>
</n:Route>
<n:Route UriTemplate="/[PageName]/[CustomerID]/[SalesOrderID]">
<n:Route.Controller>
<c:PageController DefaultResourcePath="Views" />
</n:Route.Controller>
</n:Route>
</n:RouteTable>
In this application we have three navigation routes. The first route defines no parameters just the page name, but the second and third routes add CustomerID and SalesOrderID parameters. Each route uses a PageController. The DefaultResourcePath tells the controller where to look in the application for the pages that we will navigate to.
The bulk of the application’s logic is defined in the ViewModel classes. The ViewModels implement a number of commands and properties and expose them to the UI for binding. Helix includes a number of features to help with View to ViewModel binding.
Simple properties exposed by the ViewModel are easy to bind to. In the case where the underlying data managed by the ViewModel is a collection (for example, a collection of customers), the ViewModel creates a CollectionViewModel class to wrap it. This class manages currency, selection and sorting of the underlying collection. The View and CollectionViewModel are kept in sync using the SynchronizeCollectionView attached behavior like this:
<ListBox ItemsSource="{Binding Customers}"
h:SelectionChanged.SynchronizeCollectionView="{Binding Customers}">
My post here on CollectionViewModel describes in detail how this attached behavior works. I have now rolled the CollectionViewModel and the SynchronizeCollectionView attached behavior classes into Helix so everything is in one place.
The ViewModels also implement commands that the View can bind to. Commands are implemented using the Prism DelegateCommand class – see here for more information on Prism and Delegate Command pattern. Commands can be bound to UI elements using the Prism Command attached behavior. Command parameters can also be defined using the CommandParameter attached behavior.
<Button Content="Edit"
prism:Click.Command="{Binding ViewOrdersCommand}"
prism:Click.CommandParameter="{Binding Customers.CurrentItem}" />
In the example above, we’re binding the Edit button to the ViewOrders command and passing in the currently selected customer as a command parameter. When the user clicks the button, the command’s method will be invoked with the current customer as a parameter. If the Edit command is not available, the button is disabled automatically.
Many of the commands in the application result in a navigation. Commands which result in navigation are typically implemented like this:
private void ViewOrders( Customer customer )
{
// Navigate to the Orders page.
Uri navUri = new Uri( string.Format( "/Orders/{0}", customer.CustomerID ),
UriKind.Relative );
_navigationContext.Target.RequestNavigate( navUri );
}
The Uri above is formatted in accordance with the navigation scheme that we defined in App.xaml. The Uri can include parameters such as the customer ID and these are passed to the target ViewModel when it’s created. This makes it very easy to pass parameters around during navigation. Since we have a View-First navigation application, we could also use the Helix NavigationLink control and navigate directly from the page.
The navigation context you can see above is passed to the ViewModel by the framework when it is first constructed as a result of navigation. You can use the navigation context class to get access to the navigation parameters, or to ask the navigation target to navigate to another Uri as shown above. The NavigationContext class is discussed in more detail below.
There are just a couple of final things that we need in order to stitch everything together. Since we’re using a View-First navigation controller, navigation Uris, such as the one above, specify the name of the page to navigate to. In the example above, we’re navigating to the Orders.xaml page in the Views folder. So far so good, but how does the framework know which ViewModel to create for this view?
There are a number of ways to solve this problem. Ultimately we need to know the Type of the ViewModel class so we can instantiate it. One way to get this type is to infer it from the type of the View – so, for example, a view with a type name of ‘MyApp.MyView’ would infer a ViewModel of type say ‘MyApp.MyViewModel’. This would work but means that we would have to know about the naming convention and the relevant namespaces and we would have to follow both carefully when creating our ViewModel classes.
Another approach, and the one that is implemented in this sample application, is to allow the View to explicitly specify the type of the ViewModel it was designed for. To do that we just use a simple attached property. The Customers page, for example, specifies that it needs an instance of the CustomersViewModel class like this:
<NavigationPage
x:Class="Microsoft.Samples.Helix.OrderEntrySample.CustomersPage"
...
ViewModel.TypeName=
"Microsoft.Samples.Helix.OrderEntrySample.ViewModels.CustomersViewModel">
You can imagine some day in the far flung future, when the tooling folks finally embrace the notion of separated presentation patterns, that the ViewModel’s type could be automatically specified by the tool when the user is designing the view – maybe even as a proper Type parameter making the View a generic type, for example MyView<ViewModelType>. We can only hope that that day will come soon…
In any case, when the framework creates the View it checks to see if there is a ViewModel specified, and if so, it instantiates the ViewModel and sets it as the View’s DataContext. All of this is handled by the PageController which is described in more detail below.
The last piece of the puzzle is the navigation context. Once the View and ViewModel have been created and hooked up, the controller passes in the navigation context which contains the navigation parameters and a whole bunch of other stuff. The ViewModel (or the View) can opt to receive the navigation context by implementing the INavigationAware interface, which consists of a single method OnNavigate:
#region INavigationAware Members
public void OnNavigate( NavigationContext context )
{
// Store the navigation context for later.
_navigationContext = context;
...
}
#endregion
The ViewModel can then retrieve the parameters it’s interested and retrieve the relevant data to initialize itself.
The PageController Class Dissected
The View-First application described above uses the PageController class to handle navigation. This controller does all of the heavy lifting and stitches everything together. It carries out four steps in sequence:
- The first step is to create the View. The View’s name is specified as a parameter as part of the navigation Uri, as defined in the navigation routes in App.xaml. The View is created by loading the resource, prefixed with the DefaultResourcePath if one is specified.
- The next step is to create the ViewModel. The ViewModel's type is specified using an attached property value on the View. If the View doesn’t specify a ViewModel type, this step is skipped.
- If a ViewModel has been created, the next step is to set the View’s DataContext to the it. This allows the View to binding to the ViewModels properties and commands.
- The final step is to set the navigation context on the View or ViewModel.
The last step probably needs some explanation. In part 2 of this series you may recall that we passed the navigation parameters to the target View using the INavigationPage interface. Now that we have ViewModel support, we probably don’t want to pass the navigation parameters to the page; we want to pass them to the ViewModel instead. In the latest drop of Helix, I have added a new interface INavigationAware that can be implemented by a View or a ViewModel (or both). The PageController checks to see if either the View or the ViewModel implements this interface and if so, calls the OnNavigate method, passing in the NavigationContext.
NavigationContext is a new class. It provides a single object from which to retrieve all of the information about the current navigation operation, including the navigation parameters, mode, Uri and target, etc. Most of the ViewModels in the sample application store a reference to the NavigationContext to use for initiating further navigation operations later on and for retrieving the parameters that they require.
The implementation of the PageController class described here is pretty simple. The strategy it implements is the one I settled on during my investigations, but you can easily change the implementation to suit your needs. For example, you can change the way in which the View or ViewModel gets created, or they way in which they get hooked-up, to whatever strategy you prefer. The beauty of the Helix framework is that you can make these changes in a single place without having to make multiple changes throughout the entire application!
ViewModel-First Navigation
OK, so much for View-First navigation. Let’s see what ViewModel-First navigation looks like…
To illustrate ViewModel-First navigation, I implemented a sample expense reporting application. You can run the application here. As described above, this application provides a number of tasks that the user can carry out. Each task will be rendered visually, so the user will experience these states through the UI, but to a large extent the tasks exist independently of how they are rendered.
The following diagram illustrates the tasks and the commands that lead to the transitions (navigation!) between the tasks. From the View Expense Reports task, for example, the user can create, edit, review, submit or archive an expense report; from the Edit Expense Report task the user can save the expense report and the application moves back to the View Expense Reports task.

The structure of the project is similar to the Order Entry sample described above. It consists of three folders that contain the application’s Models, ViewModels and Views, a root page and an application class.
The essential difference between this application and the Order Entry application described above is that navigation occurs between ViewModels. Each ViewModel represents a task so the bulk of the application logic is defined in the ViewModels. Each ViewModel implements properties and commands similar to those described above.
The ViewModel folder also contains a couple of ViewModel helper classes that perform data formatting for expense amounts and dates. These classes aren’t ViewModels per se, but they are used by the Views to help them render the data correctly.
There is a corresponding View for each ViewModel, defined in the Views folder. Again, the views contain no code behind.
Ok, let’s see how all of this fits together. First, the application’s navigation scheme is defined in App.xaml:
<RouteTable x:Key="GlobalNavigationRoutes">
<Route UriTemplate="/[ViewModelTypeName]/[ExpenseID]">
<Route.Controller>
<ViewModelController DefaultResourcePath="Views"
DefaultNamespace="Microsoft.Samples.Helix.ExpenseSample.ViewModels"/>
</Route.Controller>
<Route.Defaults>
<NavigationParameter ParameterName="ExpenseID" ParameterValue="-1" />
</Route.Defaults>
</Route>
</RouteTable>
This application defines a single route that has two parameters – the ViewModel type name, and the expense report ID. A default value for the expense report ID is specified, so the navigational Uri’s don’t necessarily have to specify it. This route uses the ViewModelController navigation controller class. This is the class that coordinates how the ViewModels & Views get created, hooked-up, and initialized with the navigation context.
The ViewModelController has two properties – DefaultResourcePath, which tells it where to look for Views, and DefaultNamespace, which specifies the default namespace for the ViewModel classes. The operation of this controller class is described below, but essentially it works by creating a ViewModel then a suitable View for it, hooks them up via the View’s DataContext and then sets the navigation context.
The interaction between the Views and the ViewModels is the same as described above and includes commands and the CollectionViewModel sync attached behavior. Navigation between tasks occurs as commands are invoked on the ViewModels. A typical implementation of a command looks like this:
private void CreateExpenseReport( ExpenseReport expenseReport )
{
ExpenseReport newExpenseReport = _expenseReports.CreateNewExpenseReport();
// Navigate to the Edit ViewModel.
_navigationContext.Target.RequestNavigate( new Uri(
string.Format( "/EditExpenseReport/{0}", newExpenseReport.ExpenseID ),
UriKind.Relative ) );
}
The format of the Uri is as defined in the navigation route in App.xaml. In the example above, we’re passing an expense report ID as a parameter to the target EditExpenseReport ViewModel. When that ViewModel is instantiated, the parameter will be passed in as part of the navigation context and the ViewModel can retrieve the corresponding expense report. In this way, we can control not only what gets instantiated during navigation, but also how parameters flow around the system. This really simplifies how applications like this are put together…
The ViewModelController Class Dissected
Hopefully you won’t be surprised to learn that the ViewModelController creates the ViewModel first and then creates a suitable View for it. The sequence goes like this:

- In the first step, the ViewModel is instantiated using the ViewModelTypeName navigation parameter, prefixed with the DefaultNamespace if one is specified. So for a ViewModel type name of ‘EditExpenseReport’, the type ‘Microsoft.Samples.Helix.ExpenseSample.ViewModels.EditExpenseReport’ will be instantiated.
- The next step is to create a suitable View. The details of this step are described below. If a View can’t be instantiated, an exception is thrown.
- The next step is to set the View’s DataContext to the ViewModel. This allows the View to binding to the ViewModels properties and commands.
- The final step is to set the navigation context on the View or ViewModel.
In the View-First strategy described above we had the challenge of figuring out which ViewModel to instantiate for a given View. In ViewModel-First navigation we have the opposite problem – given a ViewModel, we have to decide which View to instantiate for it.
The current implementation takes a simple approach – we just append the ViewModel’s short type name with ‘View’ and load the corresponding View resource. So for the ‘EditExpenseReport’ ViewModel, we’d load the View ‘EditExpenseReportView’ located in the Views folder. This was an experiment to see how a naming-convention based approach would work.
There are other ways to solve this problem, but for the purposes of this sample, it works pretty well. You can always implement an alternate strategy in a custom controller class if you prefer a different way to create and hook-up the ViewModel or View.
End of Part 3
Well, that was a long post wasn’t it? We covered a lot of ground though. Since we’re building Helix from the ground up there are a lot of details to grok, and just like sausages and laws, it’s not always pretty seeing how things are made. The final framework, though, should be drop-dead simple to use – that’s the goal anyway!
We’ve been experimenting with alternate approaches to discover their advantages and disadvantages and to see which one might work as a default approach that will work for most applications. We’ve essentially identified two broad approaches that have potential and we can now build applications with a View-First navigational style, or with a ViewModel-First navigational style.
Which approach you use depends on your application and which approach feels most natural to you. The implementations described here work pretty well for both approaches but there are few things that need some improvement. The nice thing about Helix, though, is that it’s simple to implement alternate strategies or to tweak the behavior of the navigation scheme in an application. With a few changes here and there we can customize navigation without having to rewrite big chunks of our application.
Personally, I believe the ViewModel-First approach has a lot of advantages over View-First approach, but it takes some getting used to. The example above doesn’t really highlight the advantages of this approach in terms of testability and UI flexibility. I’ll try and focus on those in the next post in the series, as well as deep linking. I promise that you won’t have to wait as long for that post…
On another note, whatever approach we choose, there is always the ‘tooling problem’. In other words, what would the ideal tooling experience be like for building applications based on both a separated presentation pattern and a flexible navigation system? It’s not an easy question to answer. I have some ideas but they will have to wait for a future post too…
As always, please let me know what you think of Helix – what you like or don’t like, etc. If you have any feedback on Helix, please drop me a line.
oO------Oo
Helix 0.3: Changes and New Features
A quick summary of the main changes and new features in this drop of Helix:
- Added support for global routes. Global routes are managed by the Navigation Manager and can be defined as an application-level resource in XAML. If not global routes are defined, a default global rout is added automatically. Frame-local routes can also be defined and are checked for a match first during navigation. If a match at the Frame level is not found, then the global routes are checked. This provides a lot of flexibility when implementing hierarchical navigation scenarios in an application.
- Moved the page loader code to the static Navigation Manager class. Centralizing this code allows for multiple controller classes to take advantage of it (and allows for it’s ultimate replacement by the Silverlight framework itself if and when it supports the ability to load pages by resource name).
- Removed the need to register the application’s main assembly with the Navigation Manager class. The Navigation Manager now searches all assemblies in the application manifest (except those beginning with System). This also the Navigation Manager to instantiate Views and ViewModels without the developer having to specify which assembly they are defined in, which in turn allows for easier integration between UI and non-UI application layering.
- Default constructors added for Route and Journal classes. Using the default constructor for a Route object instantiates a default PageController instance. Similarly, using the Journal’s default constructor instantiates a default RouteNavigationHandler instance. These default constructors allow for simpler declarative setup in code or XAML.
- NavigationParameter and related classes were also changed to support default construction and the ability to declaratively specify default values in Routes.
- Refactored the regular expressions in the Route class to const strings to allow for easier customization. Also tidied up the regular expression for identifying fields in the navigation Uris. This allows you to more easily change which characters are allowed in navigation fields (e.g. you can now define fields that include period and dash, so you can use GUIDS for example).
- Refactored all Controller and Journal classes into their own namespaces.
- NavigationUIVisibility is now in the Helix Controls namespace.
- Controller parameters – added the ability for a controller to specify its required parameters using an attribute. This allows the controller base class to automatically check incoming parameters to make sure that all required parameters have been provided. This simplifies error handling and the implementation of derived controller classes. This also allows for the associated Route object to check for a compatible controller when the Route is first registered.
- Navigation Context – Added Navigation Context class which includes all of the information pertaining to the current navigation operation, including the navigation parameters, original Uri and the navigation target. This provides for a simple API, better extensibility and allows ViewModels to store a reference to their navigation context so they can initiate or initiate/cancel/redirect a navigation operation.
- Added PageController and ViewModelController classes. Removed the NavigationPageController class (this functionality is now provided by the PageController class). The PageActionController class is now derived from the PageController class.
- Added DefaultResourcePath property on PageController & ViewModelController to allow views to be loaded from a sub-folder in the project. The previous version of Helix required all pages to be defined at the project root level.
- Added InitialUri dependency property on the Frame Control. This allows the Frame to navigate to the specified Uri when the Frame is first loaded, removing the need for code behind in the root page.
- Added CollectionViewModel to Helix library. Also added a number of bug fixes in the Refresh and OnModelChanged method. The latter is required due to weird behavior with the Silverlight DataGrid control.
- Added a unit test project with unit test for Routes, Navigation Manager, Page and ViewModel Controllers, CollectionViewModel, etc.
- That’s all the changes I can remember…
A quick note on Silverlight 3.0 Beta: Helix and all of the associated samples are built for Silverlight 2.0. However, you should have no problem using Helix with the Silverlight 3.0 Beta. There are a few known issues in Silverlight 3.0 Beta to do with memory leaks but these probably won’t affect you too much and they’ve been fixed in later versions.
Mix 09 starts today! There have been a number of key announcements made at Mix, especially concerning Silverlight 3.0 and Blend 3.0. If you are at all interested in Web and Silverlight development then be sure to check out the "Gu's" keynote highlights here.
The next releases of Silverlight and Blend have lots of interesting features. I'll cover them in detail in a future post, but one question that I'm sure is top of mind is how the new version of Silverlight relates to Prism and Helix.
Silverlight 3.0 provides a lot of new features that are nicely complementary to Prism. These new features help with data validation, data forms, navigation and with accessing business entities over the network. Prism focuses on patterns for flexible, modular, loosely coupled, unit-testable applications. These patterns can of course be used in Silverlight 3.0 just as effectively as in 2.0. The combination of Prism and the new Silverlight features provide a very powerful platform for building line of business RIA applications.
We're planning the next release of Prism which will target Silverlight 3.0 (and WPF 4.0), so we're beginning to look at how we can evolve Prism to further integrate and complement Silverlight, Blend and WPF. We're especially looking forward to support the new Silverlight out-of-browser feature(!). So if you have any ideas on what you'd like to see in Prism 3.0, please send them our way!
You'll also see that Silverlight 3.0 now has some support for navigation! I was part of the team behind the navigation features in Silverlight 3.0 last year before moving to the patterns & practices team. My original design for Silverlight navigation was of course very similar to Helix. The design changed quite a bit since I left that team, specifically so that it is more compatible with WPF's navigation model. I'll be posting details on the differences between the two designs, the advantages and disadvantages of each, and how to use them together soon.
We just posted a refresh to the Prism 2.0 bits. You can download the latest release from the same location on MSDN here.
The recent release of the GDR update to Silverlight 2.0 (which takes Silverlight from version 2.0.31005 to version 2.0.40115) causes a problem when building the Composite.Silverlight.Tests project. This issue only affects the unit tests and there is no change required to the core library or any of the quick-starts or the reference implementation. The issue was due to an incorrect path in one of the batch files in the unit test project. You can read more details on the issue here.
While we were refreshing the bits, we thought we'd also slip in a fix to a recently reported issue with view activation in tabbed regions. This issue caused a difference in behavior between Prism 1.0 and 2.0. You can read the details here. This issue has been fixed with the refreshed release.
We also just released a PDF version of the Prism 2.0 documentation so you can print it more easily. You can download the PDF file from here.
Coming Soon! We are working on Visual Basic versions of the quick-starts and documentation. I'll post more details once we've released these in the next week or so...
WooHoo! Prism 2.0 is done and is now live on MSDN! You can access the Prism 2.0 documentation here, and download the code from here.
Prism is a library of patterns that help you build robust, flexible and modular WPF and Silverlight applications. These patterns also support unit testing, separation of concerns, loose coupling and the ability to share application logic between Silverlight and WPF applications. The download includes the source code for the library itself, extensive documentation, a sample application that shows how the patterns work together in a real-world application, and a whole bunch of quick-starts and how-to's. There's even a snazzy Visual Studio add-in to help you easily share code between WPF and Silverlight
.
The Prism team has been busy writing blogs and recording videos to get the word out...
Blaine Wastell (program manager extraordinaire for Prism) chats to Adam Kinney about Prism on Channel 9 here. He's even written a blog post on Prism here.
If you haven't had enough Blaine you can catch even more of
him here on Channel 9, alongside Bob Brumfield (one of the developers of Prism), as Ajoy Krishnamoorthy (our product manager) ponders the eternal question - What is Prism? Ajoy's post on the release is here and Bob's is here.
Still hungry for more information on Prism?
Check out Erwin's post here, and Julian's post is here. Erwin and Julian were part of the super-talented Prism development team. Expect more videos and posts from the dev team on how to use the various super-cool features of Prism soon.
And last but by no means least, Prism's test lead Larry Brader has a post here. Larry's going to be delivering a whole series of posts that will tell you everything you ever wanted to know about unit testing and acceptance testing in WPF and Silverlight, so be sure to check his blog often.
Implementing a Master-Detail style UI with the CollectionViewModel I described in my previous post is pretty easy. With a selector control bound to a CollectionViewModel as shown in my previous post, you just need to add a content control to the View and bind its Content property to the current item and define how you want it to be rendered by defining a data template.
For the sample in my previous post the view's XAML contains this:
<ContentControl Content="{Binding Path=Catalog.CurrentItem}">
<ContentControl.ContentTemplate>
<DataTemplate>
...
</DataTemplate>
</ContentControl.ContentTemplate>
</ContentControl>
Note: In WPF, you strictly only need to bind the content control's Content property to the Catalog - WPF automatically binds to the Catalog's current item for you. Not sure why they did it this way. I think an explicit binding to the CurrentItem property is easier to understand, and I don't mind typing the extra characters. Sometimes a little more is definitely more :-)
You can run the updated sample here and download the updated source here. I also updated it to use the final release assemblies from Prism 2.0, and fixed a glitch in the Silverlight Unit Testing assembly references...
In this post, I'm going to describe an implementation of ICollectionView for Silverlight that allows you to add sorting, filtering, grouping and selection tracking to any Selector based control (such as ListBox or ComboBox). To demonstrate the implementation, I’ve built a sample application that displays a catalog of items that the user can filter, sort, group and select. You can run the sample here, and you can download the source code, complete with unit tests, from here.
In my last post I outlined the key features of the ViewModel pattern and said that WPF's CollectionViews were actually good examples of the ViewModel pattern applied to collection-based models. In this post I explain in more detail why I think of CollectionViews as ViewModels. In fact, the techniques described in this post can be used to implement any kind of ViewModel and are not restricted to just CollectionView scenarios.
CollectionViews In WPF
Before we get stuck into the Silverlight implementation, let's take a quick look at WPF's CollectionView support. MSDN has a pretty good overview of CollectionViews in WPF here, and a related sample application here that allows the user to view and edit a collection of items for sale on an auction site. The interesting thing from our point of view is that it shows the basic capabilities of the CollectionViewSource class, the related classes that implement the ICollectionView interface, and shows how they all work together. If you look at the code, you’ll see that the application’s UI has a ListBox that’s bound to a CollectionViewSource, which in turn references a collection of AuctionItems.
<Window.Resources>
<CollectionViewSource x:Key="listingDataView"
Source="{Binding Source={x:Static Application.Current},Path=AuctionItems}" />
</Window.Resources>
<ListBox Name="Master"
ItemsSource="{Binding Source={StaticResource listingDataView}}">
</ListBox>
CollectionViewSource just acts as a kind of XAML friendly factory for dishing up objects that implement the ICollectionView interface. You can also bind a control directly to a collection and a default ICollectionView object will automatically be created.
There are two main implementations of the ICollectionView interface in WPF - BindingListCollectionView, and ListCollectionView for wrapping IBindingListView/IBindingList collections, or IList collections respectively. In the sample above, the underlying collection of AuctionItems is based on IList (it derives from ObservableCollection) so a ListCollectionView object is created automatically and bound through ItemsSource to the ListBox.
The ListBox control interacts with the CollectionView through the ICollectionView interface so that the UI and the underlying CollectionView are always kept in sync. This interaction is two-way. If the user selects an item in the UI, the CollectionView’s CurrentItem and CurrentPosition properties are updated automatically. If the CollectionView’s selected item is changed (say, due to application logic), the UI is updated to show the corresponding item in the UI as selected. If the user decides to filter, sort or group the items through the UI, the CollectionView is updated accordingly. If the CollectionView is filtered, sorted or grouped due to some application logic, then the UI is automatically updated. It’s this automatic two-way interaction between the control and the CollectionView that makes them so useful.
CollectionView == ViewModel
Whatever implementation of ICollectionView you use, these classes wrap the underlying collection and provide a ‘view’ on top of it that tracks the current selection, and sorts, groups or filters the underlying collection ready for display in a UI of some sort. They sit between the UI (the View) and the underlying collection of objects (the Model) and act as a go-between to manage presentation logic and state. In other words, they are ViewModels!
Let me elaborate on that a little – by presentation logic and state I am referring to logic and state that defines the behavior of the application, but which is not specific to the application’s business logic and data or to the visual representation of the application. In this case, the presentation logic manages the selection, filtering, sorting, grouping of items in a collection. This doesn’t affect the data in the application or ensure its integrity, and we don’t want to persist this information to a back-end database, so it’s clearly not business logic or state.
It also has nothing to do with the UI – yes, it drives the UI, but we can visually represent it in many different ways, so it’s not specific to the UI. Some developers mistakenly treat ‘Selected Item’ state as specific to the UI but that leads to critical application behavior that is very hard to unit test – for example, if you had an app that displayed a list of expense reports to approve or deny, wouldn’t you want to test that the application approves or denies the right expense report?!?
CollectionViews In Silverlight
Unfortunately Silverlight 2.0 doesn’t support CollectionViews out of the box. The ICollectionView interface is defined, but there are no public implementations of this interface that you can use out of the box. Also, none of the Silverlight 2.0 controls have any built-in support for ICollectionView so even if there was an implementation that we could use, the controls won’t automatically track or update the selected item in the CollectionView.
Note: The DataGrid control (specifically, the December release, NOT the one that ships with Silverlight 2.0) is an exception – if you bind the DataGrid to a collection, it will create an internal CollectionView that tracks and updates the selected item and provides support for sorting the collection by clicking on the column headers. Unfortunately, this implementation is not available for use with other controls.
So, to have CollectionView support in Silverlight we need two things – an implementation of the ICollectionView interface, and some way for the controls in our UI to interact with it (without code in the View’s code-behind file!). The implementation in this post tackles both of these issues. Let’s take a look at each in turn.
The CollectionViewModel Class
The CollectionViewModel class in the sample code implements the ICollectionView interface and the required logic to support selection, filtering, sorting and grouping for an underlying collection model. I chose the name ‘CollectionViewModel’ because 1) it’s a ViewModel for collections!!, and 2) so that it wouldn’t clash horribly with any existing classes in WPF or Silverlight.
Some notes on the implementation of this class:
- It’s a generic class and can be used to provide a ViewModel for any underlying collection of type IEnumerable<T>.
- It derives from ObservableCollection<T>, mainly so that I didn’t have to implement the INotifyCollectionChanged interface from the ground up, and to make it easy for the controls in the View to bind against it.
- You should be able to use this class in WPF, but I haven’t test it yet. If you try it, please let me know how it goes.
- This class is roughly the equivalent of the ListCollectionView class in WPF, but there are some minor differences in the class hierarchy and the interfaces that it implements.
- It uses Linq Expressions to implement the filtering, sorting and grouping functionality. I really didn’t want to implement this functionality myself from the ground up, plus I wanted to play with Linq Expressions so this seemed like a good opportunity. I am not sure that the implementation is efficient or in any way represents best practice for dynamic Linq Expressions though...
- The CollectionViewModel class implements a number of common commands (see below) that allow next/previous selection and sorting and grouping through the UI, without requiring View code-behind or commands in a parent ViewModel.
Let’s see how this class is used in the sample application.
The sample displays a shopping catalog and lets the user filter, sort, and group the items in the catalog. The app has a single CatalogView that’s bound to a CatalogViewModel. The CatalogView has a ListBox control that’s bound to the Catalog property of the CatalogViewModel. This property is of type ICollectionView and simply returns an instance of the CollectionViewModel class.
The CatalogView is defined like this:
<UserControl x:Class="Helix.Samples.CollectionViewModel.CatalogView" ...>
<UserControl.DataContext>
<h:CatalogViewModel />
</UserControl.DataContext>
...
<ListBox ItemsSource="{Binding Catalog}" ...>
</ListBox>
...
</UserControl>
The CatalogViewModel looks like this:
public class CatalogViewModel : INotifyPropertyChanged
{
private ObservableCollection<CatalogItem> _catalogModel;
private ICollectionView _catalogViewModel;
public CatalogViewModel()
{
_catalogModel = new ObservableCollection<CatalogItem>();
...
_catalogViewModel = new CollectionViewModel<CatalogItem>( _catalogModel );
}
public ICollectionView Catalog
{
get { return _catalogViewModel; }
}
...
}
A couple of things to note: The CatalogViewModel is created by the view and set as the View’s data context (this is a simple way to implement the View-First composition pattern). The CatalogViewModel’s constructor creates the model and fills it with dummy data. In a real application, the model would likely be populated via a web service and created through a data access service component.
Under The Covers
So how does the CollectionViewModel work? In a way, it’s a simple enough class because it really just implements the ICollectionView interface. The only complication is the internal implementation of the filtering, sorting and grouping.
The consumer of the ICollectionView interface can specify a filter, or one or more sorting or grouping criteria. Linq is clearly good at this kind of stuff, but since there can be one or more criteria at runtime we can’t just write a straightforward Linq query against the underlying collection. We have to build a dynamic query on the fly using Linq Expressions. So if we have multiple sort criteria, for example, the query equates to a ‘SortBy + n*(ThenBy)’ style query on the underlying collection. I’m not sure whether you’d ever want multiple levels of grouping, but the ICollectionView supports it so it’s possible I guess…
Interacting With The View
OK – we’re about half way there. If you run the code described above, you’ll get the catalog items to show up in the ListBox, and you can programmatically add filtering, sorting and grouping criteria, but as you select items in the ListBox the CurrentItem & CurrentPosition properties on the CollectionViewModel won’t be updated. In addition, if you want to provide UI that allows the user to choose how to filter, sort or group, you’ll likely have to add lots of nasty to test code to the code-behind file of the View. Blecch!
Selected Item Tracking
The next goal is to link the ListBox to the underlying CollectionViewModel that it is bound to, so that as the user selects items in the ListBox the current item in the CollectionViewModel is updated, and vice versa. We could do this hook-up in code behind but it would be much better if we could specify this behavior declaratively in the XAML. Remember, the goal is to reduce or eliminate any code behind in the View.
Attached Properties are a popular extensibility mechanism in Silverlight. They are used most often to associate a simple value to a control so that some other control can lay it out in some way – think of the Grid.Column attached property, which is used to assign a column value to a control so that its parent grid control can lay it out appropriately.
It turns out that attached properties are actually much more powerful than you might think. You can define an attached property that alters the behavior or appearance of the control to which it is attached. This kind of attached properties are often called attached behaviors, or just behaviors. The sample implements a behavior called ‘SynchronizeCollectionViewBehavior‘ that links the ListBox control to the CollectionViewModel so that the two are kept in sync with respect to the currently selected item.
You use the behavior like this.
<ListBox ItemsSource="{Binding Catalog}" ...
h:SelectionChanged.SynchronizeCollectionView="{Binding Catalog}"/>
If you run the code now, as you select items in the ListBox, the current item in the CollectionViewModel is updated. And if you programmatically select an item on the CollectionViewModel (say using the MoveCurrentToPosition method) the corresponding item in the ListBox is selected. And all with no code-behind!
Under The Covers
How does this work? The SelectionChanged class (in the Selector.SelectionChanged.cs file) defines an attached property SynchronizeCollectionView. This attached property allows the developer to specify the source ICollectionView object to be synchronized with the target control. This class and the attached property it defines together define the SelectionChanged.SynchronizeCollectionView attached property syntax shown above. This naming convention follows an ‘event.action’ pattern that we’ll also be using for commands below.
When this value is set via XAML, an instance of the SynchronizeCollectionViewBehavior class is created and ‘attached’ to the target control. When it is attached, this behavior subscribes to the target control’s SelectionChanged event (so it can update the CollectionViewModel as the user interacts with the UI) and subscribes to the CurrentChanged event on the source CollectionViewModel (so it can update the target control’s UI as the underlying CollectionViewModel is changed). The following diagram shows how this works.
To improve re-use opportunities, the SynchronizeCollectionViewBehavior class derives from a SelectionChangedBehaviorBase class, which in turn derives from a Behavior base class. You can implement other SelectionChanged behaviors, or more general behaviors, using these two base classes.
Commands
So now that we have the ListBox and CollectionViewModel selected items synchronized, we can turn our attention to commands. In our sample application, the View provides UI that allows the user to show in-stock items only, or to sort by description or price, or to group by rating. The user can also select the next or previous items in the list by clicking buttons. The View defines the UI but we want the behavior to be defined in the ViewModel where we can test it. So the challenge is how to connect the UI in the View to the corresponding behavior defined in the ViewModel(s) without having any code-behind in the View?
Prism provides a solution to this problem using the exact same attached property/behavior pattern described above. We can use that to hookup controls to command handlers defined in the View’s ViewModel. Prism provides a Click.Command behavior which can be used to hook any ButtonBase control (essentially all controls that fire a Click event) to a command handler through data binding. For the buttons that allow the user to step forwards or backwards through the catalog, we can simply set the Click.Command attached behavior on them like this:
<Button Content="Next"
p:Click.Command="{Binding Path=Catalog.SelectNextCommand}"/>
Note that the Next and Previous commands are actually implemented on the CollectionViewModel for the Catalog. These are pretty useful generic commands to have on a CollectionViewModel and can be useful in any scenario where the user wants to step through the collection.
The CollectionViewModel class implements two other useful commands – SortBy and GroupBy. These commands take a string parameter and allow the View to perform simple sorting and grouping quickly and easily without requiring any code in the View’s ViewModel. The sample uses these two commands like this:
<Button Content="Sort By Description"
p:Click.Command="{Binding Path=Catalog.SortByCommand}"
p:Click.CommandParameter="Description" />
Prism provides an out-of-the box solution for binding buttons to commands on a ViewModel. You can extend this to support any control or event by defining a suitable attached property. To show you how to do this, the sample application uses a check box to allow the user to filter the view so that only items that are in stock are shown. The check box control is attached to the ViewModel’s FilterInStock command using a CheckedCommandBehavior class. Using this, we can hook-up the check box to the command like this:
<CheckBox Content="Show In Stock Only"
h:Checked.Command="{Binding FilterInStockCommand}"/>
Putting It All Together
The following diagram shows how the sample app is put together.
You can switch out the ListBox in the View for a ComboBox or a DataGrid (December Release) or any Selector based control and the rest of the application will just work. The XAML in the View is pretty simple and there are no complicated triggers or binding expressions to worry about. Similarly, if you look at the application's code, it’s also very simple – all of the complicated code is encapsulated in re-usable classes . This makes it very easy for a UI designer to create an experience on top of a ViewModel, which can be independently developed and tested by an application developer.
A Note On Helix
You'll notice that the more general purpose classes in the sample application are in the Helix folder. I’ll be moving these into the Helix library for its next release...
The ViewModel pattern (more formally called the Model-View-ViewModel pattern, but that’s way too long winded and I’m lazy) is an increasingly popular pattern with WPF and Silverlight developers. This is largely due to its simplicity and flexibility and its inherent support in WPF and Silverlight. It helps to separate business, presentation and UI logic which in turn helps with a whole host of development and design issues.
Having a clean separation between your application’s user interface and underlying application logic means that you can unit test it independently of the user interface. Automated testing of application logic through the UI can be complex and time consuming to setup. In addition, it can be difficult to isolate errors in the user interface or application logic portions of your application when they are both tested at the same time.
Another key benefit of using the ViewModel pattern is that it allows application developers to focus on application logic while user interface designers can focus on the visual aspects of the application. This allows the look and feel of the application to be defined separately from the underlying application logic, making it easier to maintain, modify (say as a result of usability feedback) or to customize.
The ViewModel pattern also makes the application easier to understand and maintain. It also provides more opportunities for code re-use, allowing application logic to be re-used in different parts of the same application, or allowing the user interface to be tailored to specific user roles or locales, or allowing application logic to be shared between desktop and RIA versions of the same application. In all of these cases, the underlying application logic is the same though its visual representation may be quite different.
Variations On A Theme
There are many posts and articles out there that describe the ViewModel pattern (my favorite ones are listed at the end of this post), and they all seem to differ slightly in how they define or describe the pattern. This is, of course, totally reasonable. Patterns are just a way to describe a potential solution to a design problem and specific scenarios will call for a pattern to be modified to best suit the situation. I find the (invariably heated) debates that the so-called 'design pattern experts' engage in as they argue about the finer details of a pattern to be, let’s just say, tedious and unhelpful. What matters is that the spirit and the underlying principles of the pattern are understood and applied - the details don't matter nearly as much.
The ViewModel pattern is just one of many patterns that fall into the 'Separated Presentation Pattern' bucket. Essentially, the ViewModel pattern is a variation of the Presentation Model pattern (actually, some would say that the ViewModel pattern it is in fact the same as the Presentation Model pattern). Whatever your point of view, I'm going to describe what I believe are the essential features of the pattern. In my next post I'll show you some code that I've been playing with recently that applies the ViewModel pattern to collection-based models.
ViewModel In A Nutshell
So what are the essential features of the ViewModel pattern? I describe the ViewModel pattern like this:
In the ViewModel pattern, the UI and any UI logic are encapsulated in a View. The View observes a ViewModel which encapsulates presentation logic and state. The ViewModel in turn interacts with the Model and acts as an intermediary between it and the View.
All of the separated presentation patterns exist to help separate UI from application logic by placing the various flavors of application logic and the UI into distinct classes or components. The differences between the various patterns are largely due to two things: the roles and responsibilities assigned to these classes, and how these classes interact with each other. Let’s look at the ViewModel pattern in these two respects:
Roles & Responsibilities
The roles and responsibilities of the classes in the ViewModel pattern can be characterized like this:
- The ViewModel encapsulates presentation logic and state. Presentation logic is defined here as the application logic that is concerned with the application’s use-cases (or user stories, user tasks, workflow, etc) and defines the logical behavior and structure of the application. The ViewModel is NOT a control’s code behind. Presentation logic should have no idea what its visual representation will be like and should be independent of any specific user interface implementation. To maximize re-use opportunities, the ViewModel should have no reference to any specific UI classes, elements, controls or behavior (like animations). It should not derive from any UI base class (ideally it should be a POCO). It should (of course!) be unit testable and be able to function without any UI at all.
- The Model encapsulates business logic and data. Business logic is defined here as any application logic that is concerned with the retrieval and management of application data and for making sure that any business rules that ensure data consistency and validity are imposed. To maximize re-use opportunities, Models should not contain any use-case or user-story specific behavior or application logic.
- The View encapsulates UI and UI logic. Views define the specific user interface for a piece of the application. Views are typically just controls that are designed to work well when bound to a ViewModel. Their specific role is to present the user with a user interface that represents the application’s underlying data and logic in the most appropriate way, and to interpret user input gestures and forward them to the ViewModel that then defines how they affect the underlying data and application state in the Model. In some cases the view may contain UI logic – application logic that is specific to the user interface implementation – in the view’s code-behind file. However, such UI specific code is difficult to test and should be avoided as much as possible. Of course, there will be times when the View will have specific behavior that cannot be expressed declaratively in XAML so there may be some code in the View's code-behind, but this code should be specifically focused on managing the UI controls in the View and should not implement presentation logic.
Interactions
The next thing to consider is how they interact with each other. The key here is to understand the two-way interaction between the View and the ViewModel. I think the essential feature of the ViewModel pattern is that the View is an observer of the ViewModel, which means that the ViewModel doesn't have a direct reference to the View. The ViewModel acts like a state machine and the View's responsibility is to render the state in whatever way is appropriate, and to influence that state by interpreting user input gestures.
The View typically extracts state from the ViewModel through properties that the ViewModel provides and changes of state in the ViewModel are communicated through events and notifications that the View consumes. In the other direction, the View captures user input gestures and interacts with the ViewModel to change its state. This can happen in a number of ways. The View can simply set a value on a property provided by the ViewModel. More complex state changes can be achieved through action methods that are exposed by the ViewModel.
The ViewModel Pattern in WPF and Silverlight
You may have noticed that in the description of the ViewModel pattern above I don't make any mention of any specific WPF or Silverlight frameworks features. This is intentional since a pattern should be technology agnostic. Most of the posts and articles that describe the ViewModel pattern focus on the specific features of WPF and Silverlight that directly support the ViewModel pattern. In fact, these features do such a great job of supporting the ViewModel pattern that it becomes difficult to separate them from the pattern itself.
Let’s look at some of these features and see how they support the ViewModel pattern...
Data Binding: WPF and Silverlight data binding make it easy to bind a View to a ViewModel. Data bindings can be defined declaratively in XAML and are very flexible – you can pretty much bind anything to anything. The View’s DataContext references the ViewModel so that the View’s data bindings resolve to its properties and events. Two way data binding takes care of retrieving state from the ViewModel for presentation in the View, and for updating state in the ViewModel as a result of the user’s interaction with the UI. Change notifications fired by the ViewModel allow the view to be automatically updated whenever the ViewModel’s state changes.
Commands: While data binding provides a great mechanism for supporting two-way interaction between the View and the ViewModel for state exposed as properties, the ViewModel will often provide methods that represent actions that the user can initiate through the UI – submit an order, approve an expense report, etc. Commands provide a good solution for this. They allow controls in the View to be easily associated with actions that the user can carry out without requiring any UI logic glue code, and they allow the visual representation of the action (i.e. the UI) to be cleanly separated from the actual implementation of the command (i.e. the handler). WPF has much more extensive support for commands than WPF, but the basic mechanism can be used to allow a View and a ViewModel to interact cleanly.
Data Templates: The Data Template feature of WPF and Silverlight allow you to define a View entirely declaratively. This is great for Views that require no UI logic (no code behind) and are ‘pure’ UI. Data templates contain controls and their associated bindings. When a template is applied, its DataContext is set to the object that it's templating (in our case, the ViewModel) and the bindings take over. Data Templates allow you to focus on the presentation logic in the ViewModel and leave the ‘skinning’ of your ViewModel to a UI designer who can use a tool such as Blend to built the template without having to write any code whatsoever. WPF supports implicit data templates so you can associate a data template with a ViewModel type and wherever the system sees a ViewModel of that type, the data template will automatically get applied. Silverlight doesn’t yet support implicit data templates, but you can manually specify the data template for individual controls. Finally, WPF Data Template Selectors allow the system to choose a data template based on custom logic, say to account for user roles or location.
CollectionViews: I think WPF’s CollectionViews are actually good examples of ViewModels. They specifically support models that are collection based and they encapsulate presentation logic and state to support filtering, sorting, grouping and selection. They are easily consumed by Views through data binding, are independent of the UI and support unit testing. Silverlight doesn’t yet have as much support in this area, but it does provide the ICollectionView interface so you can implement something equivalent (this is the subject of my next post so stay tuned!!).
There are many other features in WPF and Silverlight – such as Styles, Visual State Manager, Triggers*, etc – that indirectly support the ViewModel pattern but the ones described above are the big ones. All of these features work together to help the View interact cleanly with the ViewModel. By ‘cleanly’ I specifically mean that they reduce the amount of UI specific code that is required to glue everything together.
* As a side note, I am not a big fan of triggers. They are very useful in some situations for defining visual behavior, but they can also be (mis-)used to define presentation logic in the view which is bad. I find the Visual State Manager a much better mechanism for defining visual behavior…
The Right Code in the Right Place
To summarize, getting the right code in the right place is the key to leveraging the ViewModel pattern to build flexible, robust WPF and Silverlight applications. Deciding where a specific piece of code should go can sometimes be difficult, but it gets easier with practice and the features that WPF and Silverlight provides help simplify this process dramatically.
More Stuff On ViewModel
Here’s a short of list posts and articles on the web that I’ve found the most useful and interesting
oO------Oo
For those of you who are keenly awaiting my next post on navigation in Silverlight, this post and my previous post on view-first and presenter-first composition are really parts 2a and 2b of that series. I’ll be building on the concepts that I’ve described in these posts and focusing specifically on how navigation and the ViewModel pattern interact. Sorry it’s taken so long, but hopefully it’ll be worth the wait :-)
The long awaited 2nd edition of the patterns & practices Application Architecture Guide has just reached content complete status. Congratulations to J.D. and the whole Application Architecture Guide team on a superb job! You can download the content complete version of the guide from the CodePlex site here.
The Application Architecture Guide is one of our most important releases this year. Painting a coherent picture for an area as deep and wide as application architecture is very difficult, but judging by the download numbers (nearly 37000 in less than a day!) the community is clearly looking for this kind of guidance.
The guide itself is really the tip of the ice berg. J.D. and team have made much more content, including how-to's and videos, available at the Application Architecture Guide's Knowledge Base site here. Check it out and let us know what you think.
Next step for the guide is final editing, getting it published to MSDN and printing it in book form, so be sure to look for it in a book store near you soon!
Long time P&P friend and collaborator David Platt of Rolling Thunder and 'Why software Sucks!' fame is providing online training for Prism 2.0!
It's a three day course to be held March 2-4, and looks like it covers everything from the goals and basic architecture of Prism, to modularity, UI composition, pub-sub eventing, and services - everything you need to get up and running with Prism. Check out the course details here, and the detailed course syllabus here. David is a lively and knowledgeable speaker so it should be fun too.
When I was a kid growing up in England, one of the things I looked forward to the most at Christmas was the Royal Institute Christmas Lectures.
The Christmas Lectures are aimed at kids (even grown up ones!) and cover all sorts of subjects in science and technology. My favorite lectures were always on astronomy or mathematics (yes I was a geeky kid, and proud of it). Their aim is to get kids interested in science and technology, an increasingly important goal these days, so they're full of demonstrations, experiments, and rich graphics.
They have been given every year since 1825 (apart from a short break for World War 2), the first lectures being given by Michael Faraday himself, and have been televised since 1966. Over the years some pretty famous scientists have given the lectures, including David Attenborough and Carl Sagan. One of the most endearing things about the Christmas Lectures is the super-geeky lecturer, who’s clearly at the top of their field, wearing a bright Hawaiian shirt in an effort to look cool and trendy to the kids :-)
This year's lecture is being given by Prof. Chris Bishop who's going to be talking about the science behind the digital revolution – everything from the microchip to the internet to digital intelligence. I was pleased to find out that this year’s lectures are beings sponsored by Microsoft Research. If you’re in the UK you can catch them on Channel 5 beginning on December 29th at 7:15PM. There are five lectures in the series and they air each day at the same time. Previous lectures are available as web casts here.
If you have kids, nieces, nephews, or younger siblings encourage them to watch. Science and technology will need all the IQ we can muster over the next 50 years if we’re to survive and prosper. Just don’t let the bright shirt put them off…
Figuring out the right name for something is one of the hardest things in software development. There is a lot to a name – the name conveys the concept; get the wrong name and you convey the wrong concept, leading to much confusion, developer irritation and mental pain.
We’re currently working on a new capability in Prism 2.0 that we’ve been calling ‘top-down’ or ‘view-first’ composition. We’re not really sure whether either of those specific names clearly and succinctly describes what this capability is all about, and so we’ve been having many discussions on the team about what it is exactly that top-down/view-first composition achieves and how it relates to other types of composition. If we can be really clear on those two things, then maybe we can figure out what the best name for it is. In this post I’ll describe what top-down/view-first composition is and how it relates to other types of composition. At the end I hope you’ll agree that ‘view-first’ is a reasonably good name for it. But, if you can think of a more appropriate name we’d dearly love to hear it!
Let’s start by defining composition as simply taking a bunch of ‘things’ and combining them to build an application. Different composition patterns describe different ways of composing an application, either by using different ‘things’, or by using a different way of combining the ‘things’. As always in software development, there’s more than one way to skin a cat (apologies to any cats or cat lovers reading this blog) so it isn't surprising that there are different composition patterns, each with its own advantages and disadvantages. Perhaps the most commonly used composition pattern though is the traditional ‘forms and controls’ pattern. Let’s walk through this pattern first and then we can contrast and compare other composition patterns to it.
Forms And Controls
Ah, good old-fashioned forms and controls. Where would we be without forms and controls? They have been the staple diet of UI tier application developers forever (well maybe not forever, but an awfully long time).
Using this composition pattern the developer will build an application by creating a number of forms. On each form they’ll drop one or more visual controls. They’ll configure the controls by setting various properties and then add code to the form to ‘wire’ the child controls up and implement the form’s business logic. The developer will often build controls of their own, and these will often be fairly sophisticated app-specific composite controls that contain many child controls. In fact, since forms are really just specialized types of controls, we can just think of this whole approach as ‘Control-Based Composition’.
The app is essentially the hierarchical combination of all of the controls and the code that wires them together. In this composition pattern then, the ‘things’ are visual controls, and the application is composed by assembling visual controls into higher-level controls and linking them together with code. It’s easy to provide a visual tooling experience for constructing applications in this way, and it’s relatively easy to understand the internal structure of an application by following its visual structure.
Control-based composition is pretty much the default experience that you get in almost all current tools and visual development environments, including Visual Studio, Blend, etc. Developers have been generally happy with this approach over the years – it’s simple, visual and designer friendly – so what’s the problem? Well, there are two related drawbacks to this approach – what I’ll call ‘Tight Coupling’ and ‘Overlapping Concerns’. Let’s take a look at each of these:
- Tight Coupling – Since the developer explicitly chooses the controls at design-time, they can very easily make their application tightly coupled and inflexible. By choosing specific controls and writing code against that specific set of controls, it’s very easy to introduce strong dependencies that are dispersed throughout the entire codebase. These dependencies can be very hard to manage and can limit re-use opportunities and lead to static, brittle, hard to maintain, almost impossible to extend applications. They can make it very difficult to extend or modify the application without requiring (sometimes substantial) code changes, recompilation, and re-deployment of the application.
- Overlapping Concerns – Most control models (all of the ones that I know of anyway) tend to define controls as single classes, and the control encapsulates both its UI and its business or presentation logic within this one class. From the consumer’s point of view, the class has an API and they code against that in the form or containing control. WPF and Silverlight have added the (absolutely fantastic) ability to re-style or re-template controls, which can help separate the controls UI from its behavior, but the control is still one class. For generic low-level controls (like buttons, text boxes, etc) this works great since they contain no business or presentation logic (just control logic). But for app-specific controls or forms (like, say, a CustomerList or CustomerContacts control) the control will typically mix visual aspects (e.g. BackgroundColor) with business or presentation logic aspects (e.g. AddCustomer, AddOrder). This can make it very difficult to test any business or presentation logic within the control without having to use some kind of UI automation or manual acceptance testing.
Neither of these two issues are intractable. The tight coupling problem can be addressed by adopting patterns that introduce loose coupling and that help manage dependencies – like modularity and dependency injection, etc. Using these patterns tends to alter the way in which the ‘things’ get composed into an application, but they tend not to affect what those things are. In this post, we’re going to focus mainly on the problem of overlapping concerns. We’ll see that the patterns that are used to address this issue generally lead to a change in the ‘things’ from which the application is composed.
Separated Presentation Patterns
One of the most popular remedies to the overlapping concerns issue is the introduction of a Separated Presentation Pattern (such as Model-View-Presenter, Model-View-ViewModel, Supervising Controller, etc, etc). I’m not going to detail the many different separated presentation patterns you could use here – it’s a big and somewhat nuanced subject – but suffice it to say that regardless of the actual pattern you choose, they all are concerned with separating out the purely visual aspects of a control from the business or presentation logic by encapsulating each into separate classes. For simplicity, I’ll call the class that encapsulates the visual aspects the ‘View’ class, and the class that encapsulates the presentation logic the ‘Presenter’ class (yes, different patterns use different names for these two classes, but the net result is the same so bear with me).
The two key benefits of adopting a separated presentation pattern are that you can unit test the behavioral/logic aspects of the control without having to automate it through the UI or do manual acceptance testing, and that you can more easily change the UI of the application while keeping the business or presentation logic completely untouched. There are other distinct benefits too, like being able to have your developers (who are typically bad at UI design) focus on app logic, while your UI designers (who are typically bad at writing app-logic) focus on the look and feel of the application. Another benefit is that since the View and the underlying Presenters are loosely coupled, the app can be more flexible and dynamic and choose (based on, say, the user’s role, current task or preferences) how best to render the application’s UI while re-using the exact same underlying Presenter.
With View and Presenter classes in the mix, what happens to the composition pattern? This is where things get interesting since we now have more ‘things’ with which we can compose. Essentially, the developer can choose to compose the application in one of two basic ways:
- Compose the application from the Presenters, and then have the corresponding Views somehow created and wired up.
- Compose the application from the Views, and then have the corresponding Presenters somehow created and wired up.
Not surprisingly, I’m going to call the first one ‘Presenter-First’ composition, and the second one (you guessed it!) ‘View-First’ composition. These two patterns represent two points on a spectrum and its possible to use both patterns in the same application, or to use a hybrid pattern that combines features from both, depending on your requirements or preference. In the next couple of sections, I’ll drill into each of these and describe their respective advantages and disadvantages.
Presenter-First Composition
In the Presenter-First composition pattern, the ‘things’ are primarily Presenters, and conceptually the application is composed by assembling/wiring Presenters together. The Presenters then pull in the Views that they depend on which then get inserted into the app’s UI.
With Presenter-First composition, the process goes something like this:
- The Presenter is created first.
- The Presenter (or some other entity) then creates a View and connects it to the Presenter.
- The View gets shown in the correct position in the UI.
There are many different ways of achieving each of these steps. Because of the variations that are possible at each of these steps, Presenter-First is really a general approach rather than just a single specific approach. Some variations to consider:
- When a Presenter is created, its typically wired up to communicate with other Presenters (either in a peer-to-peer arrangement or in a parent-child arrangement) and with other Models and Services. Often, Dependency Injection is used to help create and wire up Presenters to other objects.
- The Presenter itself can be responsible for explicitly creating a View for itself and then expose it through a property (e.g. MyPresenter.View). It’s not likely that the Presenter will create a specific View class – this would reduce flexibility and introduce tight coupling – it’s more likely that the Presenter will use a DI container or some form of configuration driven mechanism to create a suitable View. More often, the View creation mechanism is external to the Presenter and Views can be created implicitly (as is the case when using implicit DataTemplates in WPF) or explicitly by using a View factory of some sort that creates an instance of a specific View class according to some external configuration.
- Once the View is created, it is ‘connected’ to the Presenter. I personally dislike any model where the Presenter has explicit knowledge of a View (say through an IView interface reference) regardless of how the View was created. I much prefer the model where the View is an observer of the Presenter and the Presenter goes about its business altering and managing its state, according to the presentation logic it encapsulates, and the View updates itself accordingly through bindings and behaviors. I’ll be posting much more on this in a later post…
To some developers, presenter-first composition feels more natural and ‘pure’ since the View creation can be abstracted away allowing them to focus on the logical non-UI structure (Presenters and other non-UI Models and Services) of the application. For any one particular use case or screen in the application, one or more presenters will be in play and the developer can write unit tests for this combination of presenters without having to test by automating through the UI. In extreme cases, the application may even be driven completely ‘headless’ and not require a UI at all, and be able to be driven through a command line interface (nice for the purists but not generally useful IMHO).
The downside with this approach is that it tends to be complex, making it very difficult to understand how the various pieces of the application get created and connected together. Since the UI is constructed at run-time as a result of the interaction of many components, to understand the structure of an application, you often have to spend many happy hours in the debugger tracing through everything and seeing what gets created, when and by whom. It also is very difficult to provide any kind of visual tooling experience for applications constructed in this way.
You can see this composition pattern in action in Prism 1.0 in the UIComposition quick-start. This example implements a simple project management application made up of 2 separate modules – an Employee module that provides general information on a list of employees, and a Projects module that provides details on their current projects. The Projects module has a ProjectsListPresenter, ProjectsListView and a ProjectService. A controller class, the EmployeesController class, is used to coordinate and stitch everything together.

When the user selects a particular employee in the UI, the EmployeesController constructs a Presenter using the container:
IProjectsListPresenter projectsListPresenter = this.container.Resolve<IProjectsListPresenter>();
The DI container constructs the Presenter class and injects any dependencies that it may have. In this case, the Presenter has dependencies on a ProjectsListView and a ProjectService. The container dutifully creates those objects and passes references to a them into the Presenter’s constructor.
public class ProjectsListPresenter : IProjectsListPresenter
{ private readonly IProjectService projectService;
public IProjectsListView View { get; set; }
public ProjectsListPresenter( IProjectsListView view, IProjectService projectService )
{ this.View = view;
this.projectService = projectService;
}
}
Note that all of these types are registered with the container in the Projects module’s Initialize method so the container knows how to resolve everything:
this.container.RegisterType<IProjectService, ProjectService>();
this.container.RegisterType<IProjectsListView, ProjectsListView>();
this.container.RegisterType<IProjectsListPresenter, ProjectsListPresenter>();
Now, the astute reader might have spotted that in the code above, the View is technically constructed before the Presenter. That’s just an artifact of the fact that we’re using constructor injection in this example. The key thing is that the Presenter is logically created first, and that the Presenter has a dependency on the View (rather than the other way round).
With the Presenter and its dependent View and Service constructed and wired up, the controller needs to show the Presenter’s View in the UI somehow. To do this, we use Regions. Regions are essentially named placeholders in the UI into which arbitrary Views can be inserted. In the EmployeeDetailsView we defined a region called ‘DetailViewsRegion’:
<TabControl cal:RegionManager.RegionName="DetailViewsRegion" … >
This view is in the Employees module and doesn’t know anything about the specific ProjectListView that we want to show here. The controller is responsible for making this association. To do that it goes and looks for this region, using the region manager, and then inserts the view into it:
IRegion region = detailsRegionManager.Regions["DetailViewsRegion"];
region.Add( projectsListPresenter.View, "CurrentProjectsView" );
detailsRegion.Activate( detailsPresenter.View );
The Region is passive in the sense that it has no knowledge that any specific view (or any view at all) will be shown – it’s left to the presenter or controller to determine which, if any, view is shown and to inject that view into the region. This makes it somewhat difficult to understand the structure of the application just by looking at the UI because the placeholders are just passive named regions – in other words, the logical structure of the application can’t be easily determined from the visual structure. In addition, if a region required by module is not defined in the hosting application, the module may fail unless the developer checks for the existence of the region before trying to inject the View.
The following diagram shows the sequence of events for Presenter-First composition.
Because this approach focuses on creating and connecting the Presenters, Models, Services and other non-UI components first, and then creating Views and pushing them up into the UI second, we’ve also been calling this approach Bottom-Up Composition. I think Presenter-First is a more accurate name though…
View-First Composition
As its name implies, View-First Composition focuses on composing the application first and foremost from Views rather than Presenters – the ‘things’ are primarily Views – and conceptually the application is composed from Views. The Views then pull in the Presenters that they depend on.
With View-First composition, the process goes something like this:
- The View is created first.
- The View (or some other entity) then creates a Presenter and connects it to the View.
- The View gets shown in the correct position in the UI.
Again, there are many different ways of achieving each of these steps and View-First is really a general approach to composition.
The principal difference between View-First and Presenter-First is that the View has a dependency on the Presenter, rather than the other way round. View-First is a composition pattern that lies somewhere between the traditional Control-Based composition and Presenter-First composition. One of its primary benefits is that it makes it easier to construct applications than with the Presenter-First approach, while retaining the loosely coupled, pluggable, unit-testable benefits of using a separated presentation pattern. This pattern also makes it much easier to understand the structure of a given application by allowing you to follow the visual structure, reducing the need to track code execution in order to understand how everything is created and connected together.
Let’s see View-First composition in action. We’ll use the same example as above and show how the same application would be composed using this approach.
Disclaimer! We’re still working on this so some of the code below is just an illustration of how this capability could work, and we may or may not implement it as shown here – your feedback would be great to have on this.
When the application runs, the EmployeeDetailsView is shown. As before, this view defines a region where the project list for the currently selected employee will be displayed.
<TabControl cal:RegionManager.RegionName="DetailViewsRegion" … >
Whereas in Presenter-First composition the region is passive and waits for a view to be injected into it by a controller, in View-First composition the region will proactively go and create any views that are registered to be shown in this region. When the EmployeeDetailsView is shown, the region manager will go and see if any views have been registered for the DetailViewsRegion. Views are registered with the region manager in the module’s Initialize method:
this.regionManager.RegisterViewForRegion( "DetailViewsRegion", typeof( ProjectsListView ) );
You can think of this as the equivalent of registering a type with a DI container so it will know how to instantiate dependencies, except here we’re registering a View type against a named region so the region manager will know how to instantiate the views required for that region. Note that the parent view and the child view are still loosely coupled and we can still plug in any implementation of a view that we choose.
The ProjectsListView is now instantiated by the RegionManager, but what about the Presenter? In View-First composition, the ProjectsListPresenter is considered a dependency of the view. This dependency is expressed in the ProjectsListView declaratively like this:
<UserControl x:Class="UIComposition.Modules.Project.ProjectsListView"
cal:Presenter.Type="{x:Type UIComposition.Modules.Project.IProjectsListPresenter}" … >
After the view is created, an instance of the required presenter is created using the DI container, which incidentally will create in turn any dependencies that the Presenter has (in this case the ProjectService). Once the Presenter is created it is connected to the view by setting it as the view’s data context (so that any binding or command expressions in the view will be directed to the presenter).
The following diagram shows the sequence of events for View-First composition.
Since composition flows from the View down to the Presenters and then to the Models, Services and other non-UI components, we've been also been calling this 'Top-Down' composition. Again, I think View-First is probably a better name though.
And that’s pretty much it. With View-First composition, we have less code for the same end-result but the chief benefit is that it’s much easier to follow what happens and when. The key thing to remember is that the View is created first, then the Presenter (which is considered a dependency of the View) then any dependencies that the Presenter has. This pattern is very similar to the traditional and familiar control-based composition pattern, but with the added benefit that it’s loosely coupled and separates the UI from the business and presentation logic. It is also easy to see how this pattern can be supported by visual tools – imagine a placeholder control that you can drop onto your form and then configure to go and pull in whatever View is registered by the pluggable modules.
oO------Oo
Hopefully this all makes sense. Once you move away from control-based model where everything is in one class, to a separated presentation model which introduces additional classes, things can get complicated pretty quickly. These patterns can help make sense of this additional complexity and allow you to realize the benefits of loose coupling and a separation of concerns without imposing too much overhead...