Prism for Windows 8.1 Store Apps Available

Just the other week on Blaine’s blog there was the announcement that Prism for WinRT on Windows 8.1 had been released by the Patterns and Practices team.

I’ve talked a little about Prism for WinRT before ( here and here ).

While the Prism team talks about Prism being for “Windows Store business apps” I see it as having much broader appeal in that Prism provides a tonne of guidance around how to build a structured, high quality app along with libraries that help you in doing that and a reference implementation of a business-style app that you can examine and compare your own implementation to.

I think anyone building apps for Windows Store can gain from reading through the Prism documentation with its top level topics like;

  • Designing UX
  • Using MVVM
  • Creating and Navigating Between Pages
  • Using Touch
  • Validating User Input
  • Managing Application Data
  • Handling Suspend/Resume/Activation
  • Communicating Between Loosely Coupled Components
  • Working With Tiles
  • Implementing Search
  • Performance
  • Testing & Deploying

It’s a really good guide – it’s worth investing time in but…

Isn’t Prism and MVVM Just Too Hard ™ ?

I was at an internal event at Microsoft a couple of months ago and there was some casual chat around topics like “Model View ViewModel” and patterns in general for Windows Store apps and there were a few folks chatting on the topic and the general view seemed to be something like;

“it’s just Too Hard ™ for regular developers to pick up those kind of techniques, the barrier to entry is too high”.

But this didn’t seem right to me.

I don’t think picking up some pieces from a framework like Prism necessarily means you have to be some kind of rocket-scientist.

In fact, I think that for a “Hello World” style example the code that you need to get a Windows Store app off the ground with Prism is less than the code that ships in the blank templates.

I also think it’s simpler code and cleaner code.

Using that new version of Prism as an example,  I thought I’d just illustrate how easy and clean it is to make “Hello World”.

In the past, I took the Visual Studio Grid template and re-wired it on top of Prism so that might be something to also take a look at.

The first thing to do is to make a blank project in Visual Studio.

With that made, spark up the “Manage NuGet Packages…” dialog off the solutions “References” section and add in the Prism libraries;


The next step is to change the base class of the app from Application to MvvmAppBase in both the App.xaml.cs file and in the App.xaml file. Here is my entire App.xaml.cs file at the end of that process;

namespace App7
  using Microsoft.Practices.Prism.StoreApps;
  using System.Threading.Tasks;
  using Windows.ApplicationModel.Activation;
  sealed partial class App : MvvmAppBase

    public App()
    protected override Task OnLaunchApplication(
     LaunchActivatedEventArgs args)
      this.NavigationService.Navigate("Main", null);

      return (Task.FromResult<object>(null));

That’s less code than you would have in the standard App.xaml.cs file that is part of the blank template.

There’s no Suspending event handler, there’s no logic for whether to create a Frame or not. It’s very little code. The App.xaml needs to change as well;



The one piece of code that I’ve really added to the app so far is a call to the NavigationService which tells it to navigate to a string “Main” suggesting that this is the “Main Page” for the app. There is a convention in Prism (which can be overridden) which by default will cause the framework in my app (App7) to look for a page type called App7.Views.MainPage.

The blank project already gives me a page called MainPage so it’s relatively easy to drop the 2 files (XAML and C#) that make up that page into a Views folder;


and that doesn’t cause Visual Studio to put the MainPage class into a Views namespace so it’s necessary to make a little change to the MainPage.xaml.cs file;


and the corresponding XAML file;


and that’s it. I’ve got a blank application up and running and it contains less code than the blank application template that ships with Visual Studio. It also contains fewer conceptual pieces. Here there are;

  1. An App.
  2. A Page.
  3. A Navigation Service.

whereas in the blank template you’d have all of these but at least some additional code which does something with;

  1. A Frame which also represents a navigation service for you and that can sometimes be a problem when you’d like to access the capabilities of a navigation service without having to pick up all the baggage of a Frame object.
  2. A Window.
  3. A Suspending event.

so it’s not a lot more but it is more to deal with just to get a blank page on the screen.

Adding Some Data

What if I wanted to edit a piece of data – a simple string to edit for example. It’s pretty easy to author some “UI” for that – I can edit my MainPage.xaml to add a TextBox;


this is pretty abstracted – there’s a piece of data somewhere called TheText and that’s all the UI cares about which is probably close to “as good as it gets” in terms of keeping the UI separated.

How do I feed that UI with data? By writing a ViewModel which provides the TheText value with change notification. This is pretty simple with Prism, I can create a ViewModels folder and a class within it called MainPageViewModel;

namespace App7.ViewModels
  class MainPageViewModel : ViewModel
    public string TheText
        return (this._theText);
        base.SetProperty(ref this._theText, value);
    string _theText;

and I need to tell the page that this is the ViewModel type that provides data for the page. This can be as simple as altering the XAML file;


and that’s it.

Now when I run the app, the framework will construct the MainPage and navigate some Frame (which we haven’t been exposed to) over to that page and it’ll also construct an instance of the MainPageViewModel (based on convention which can be rewired) and set that instance as the DataContext of that page for the binding to be resolved.

It’s easy. It’s logical. There’s an app, a view, a view model and they have as little knowledge of each other as possible.

What about handling something more complicated like the Suspend/Terminate Process Lifecycle Management that Windows Store apps have to deal with?

Surviving Suspend & Terminate

One of the joys (or pains Smile) of writing a Windows Store app is handling what happens when your application suspends and terminates. Even my one TextBox UI example is broken with respect to this functionality. For example, if I am running my “app” and I enter some text into the TextBox;


and I then use the highlighted “Suspend and Terminate” button to simulate the system shutting down the app before re-running the app then I see;


and so the app has lost its volatile state and the user might well consider the application broken if the time between the system terminating the app and the user re-running it was short enough that the user could remember what the app was supposed to be doing the last time they saw it.

Now, if you take a look at the Visual Studio templates you’ll know that there’s a few “moving parts” involved in saving state. It goes something like this;

A class called the SuspensionManager is linked into the Page via the NavigationHelper and that links into the Frame and when suspension occurs the Page code handles some OnNavigatedFrom event and it can save state into dictionaries which are provided by the NavigationHelper but which are owned by the SuspensionManager and  which your App class then ultimately has to save to disk in its handler for the Suspending event by asking the SuspensionManager to do that saving for it.

Then…when your app runs back up it has to register the Frame with the SuspensionManaer and then it needs to see if the PreviousExecutionState was set to Terminated and, if so, the app has to ask the SuspensionManager to re-load the saved state.

For me, this often feels like I’m being exposed to more moving parts than I need to be and those parts aren’t necessarily in a position to be able to access the data that needs saving.

In a Prism app, this responsibility for persisting volatile state could be handled by the ViewModel. 

Taking the code that I already have, I can fix the current suspend/terminate problem with my “app” by adding one attribute;


It’s easy. It’s logical. It’s not the only thing that I can do – I can take more explicit action if necessary but it’s easy to get going with.

Wrapping Up

Kicking off with a framework like Prism for Windows Store apps doesn’t have to be “hard”. Sure, there are lots of other things that you can do here to alter the convention and you can start to wire up an IoC container and so on but getting started is pretty simple and, arguably, leaves you with less code in a blank(ish) project than you would have if you just started with the built-in templates.

It might be worth giving those Prism docs and libraries a look if you’ve been there before and got the impression that there’s some big barrier to entry.

Windows 8 and Prism: Migrating a Simple Example

In some of our recent Windows Phone events, I’ve been using an example “application” (i.e. it’s a demo, not a whole app) to try and talk about an approach to structure code such that a reasonable percentage of it is portable across both Windows 8 and Windows Phone 8 and with that portable code packaged into .NET portable class libraries.

The “application” is one that presents 3 simple screens allowing you to search for photos on the flickR photo service. Screen 1 looks like this;


and Screen 2 looks like this;


and Screen 3 looks like this;


with an AppBar menu which saves the picture in question into the user’s Picture Library;


I have both a Windows 8 and a Windows Phone 8 variant of this and the implementation of this “application” tries to follow the MVVM pattern and the “architecture” ends up looking something like this (my diagram from the talk);


With the idea being that the bits in blue are all pieces of implementation specific to Windows 8, the bits in green are all pieces of implementation specific to Windows Phone 8 and the bits in the middle in black are all defined in portable class libraries and are re-used (at the binary level) by both implementations.

The structure of the app  looks like this in Visual Studio;


I have 3 views for the SearchPage, SearchResultsPage and PhotoDetailsPage. I then have 2 services that are specific to Windows 8 – one to save a photo into the pictures library and another to abstract the specifics of a navigation service so as to make it available to my view models and also so as to have a simple, cross-platform abstraction of it.

I then have a fairly standard App class and some bits to set up an Autofac container which is then later used to resolve the implementations of the services that are abstracted by interfaces in my abstractions library.

I take a “manual” approach to instantiating view models and linking them up to be the DataContext of a view (which I’d ideally move away from although it can make for a more complex demo).

In my first portable class library I have;


4 view models (plus a base class) to support the 3 views of my app;

  1. SearchPageViewModel
  2. SearchResultsPageViewModel + SearchResultViewModel (the view model behind each item displayed in the GridView in the view)
  3. PhotoDetailsPageViewModel

I also have a simple Model class (FlickrSearchItem) which represents the data that I deserialize back from flickR and then I have some code that knows how to call flickR’s API to do a search, get the results back and give me back instances of my Model class in a list.

This code (via the portable HttpClient library) turned out to be portable so I don’t currently have it abstracted but it would perhaps be better if I did have an abstraction of it so that it can be injected into classes that have a dependency on it.

I also have an implementation of ICommand in this library in the SimpleCommand class and a base class for my view models called ViewModelBase which implements INotifyPropertyChanged for me.

In my second portable “abstractions” library project I have;


so it’s just a couple of interfaces that abstract what it “means” to be a navigation service and what it “means” to be a photo saving service and those interfaces are then implemented by specific services.

Now, in talking about these ideas in an in-person session I find that I have a slightly poor signal:noise ratio because I feel I need to introduce some or all of;

  1. MVVM.
  2. Commanding.
  3. Binding and INotifyPropertyChanged.
  4. Abstraction and “services”.
  5. Inversion of Control and Dependency Injection.

and, frankly, there are areas where it’d make it a lot easier to lean on a framework and allow it to do some of this lifting for me.

Given the recent release of Prism for Windows 8 Store apps, I thought I’d take my Windows 8 version of this “application” and see what it’s like to rebuild it on top of that framework to see how much better my signal:noise ratio gets. This is my attempt…

Putting the Pieces Back Together on top of Prism

I wanted to start from scratch so the first thing I did was to make a Windows 8 project using the “Blank” template and then I added from NuGet the “Prism.StoreApps” package and then copied across a bunch of imagery that I’d used in my previous app into the Assets folder and set up the manifest to make use of them (e.g. splash screens and so on).

In the interests of initial “simplicity” I decided I’d bundle everything into a single project in the first instance so I set up a few folders;


and then got rid of MainPage.xaml.

Having done that, I brought across my views and code from my other projects omitting some pieces that I knew that Prism already had for me (e.g. an implementation of ICommand and a base class for my view models).

I changed the base class of the App class from the Visual Studio template to be MvvmAppBase from Prism rather than the Application class. I also took away all of the boiler plate code from my App class as I wasn’t sure how much of it I now needed.

I then visited my view models, taking away my original ViewModelBase base class and replacing with the Prism ViewModel class. I also refactored my FlickrService code such that I built an interface which abstracted it and then made the one view model that needed to use it take a dependency (at construction time) on that interface rather than on the implementation itself.

The other thing that I’d baked into my View Models was a dependency on a navigation service that I’d built so I took that away and replaced it with a dependency on the INavigationService that Prism provides and I overrode the ViewModel.OnNavigatedTo method on the two of my view models that needed to pick up a parameter passed by navigation (previously, I’d made this a responsibility of my own navigation service).

Where I made use of the Prism navigation service, I simply made calls like this;

    void OnSearchCommand()
      this._navigationService.Navigate("SearchResults", this.SearchTerm);

with the idea being that “SearchResults” (albeit in a hard-coded string literal!) is an abstracted token being used to navigate to my SearchResultsPage page.

Also, I took away my own use of my own SimpleCommand class and replaced it with Prism’s DelegateCommand which looks reasonably similar anyway.

In terms of my views, I took away any code which was manually resolving view models and setting DataContext values (this should never really have been present but the app I’m moving is a demo) and I also changed the base class of my pages to Prism’s VisualStateAwarePage although that’s possibly academic for this particular code. Finally, I made sure that each view was declaratively (i.e. in its XAML) setting the Prism ViewModelLocator.AutoWireVIewModel property to true.

At this point, I felt I was getting pretty close to where I’d started but there’s a degree of “wiring together” that needed to be done in order that;

  1. I navigate to my first SearchPage view when the app starts up.
  2. Navigation using a string token such as “Search” is resolved correctly to a page like SearchPage
  3. Views are able to create View Models and View Models are able to resolve the services on which they’ve taken a dependency

Apart from that, I was trying to keep my App class as “free of superfluous code” as possible.

For point 1 above, I ended up overriding the OnLaunchApplication method;

    protected override void OnLaunchApplication(LaunchActivatedEventArgs args)
      this.NavigationService.Navigate("Search", null);

so that felt pretty minimal and for point 2 I ended up overriding the GetPageType method – this was purely because the default implementation looks to expect to take a page token like “foo” and attempt to resolve it to a type called “fooPage” but it looks to expect the namespace of that “fooPage” class to be the one of the currently executing assembly. My views weren’t named that way so I overrode;

    protected override Type GetPageType(string pageToken)
      // My views are called MvvmStart.Views.{0}Page whereas the
      // base class expects something different.
      // Naturally, we wouldn't want to hardcode this namespace
      // right here in the 'real world'.
      string baseName = "MvvmStart.Views.{0}Page";
      string typeName = string.Format(baseName, pageToken);
      Type type = Type.GetType(typeName);
      return (type);

and then, finally, for point 3 above I introduced an Autofac container and overrode the OnInitialize method to set it up;

  protected override void OnInitialize(IActivatedEventArgs args)

      ContainerBuilder builder = new ContainerBuilder();




      this._container = builder.Build();

Now, I should point out that I’m no Autofac expert so feel free to critique but this is essentially registering the navigation service, flickR service, photo saving service and then my view models so that they can be created by the container with their dependencies on those services resolved.

I then overrode the Resolve() method to make use of this container;

    protected override object Resolve(Type type)
      return (this._container.Resolve(type));

and that was it. Running, “working” (i.e. seems to be working as I don’t have tests for this demo) code within around 90 minutes on a train ride home on a Saturday night Smile

One thing I’ll say that I was particularly pleased with was that my SearchResultsPageViewModel looks like this;


it has a collection of SearchResultViewModel that it needs to populate which means it has to know “how” to create a SearchResultViewModel from a container and have its dependencies resolved.

I was quite pleased with the way that Autofac handled this for me in that rather than having to take a dependency on some “container interface” I just had to take a dependency on a Func<SearchResultViewModel> and Autofac automatically injected it for me. That is, the SearchResultsPageViewModel constructor looks like;

    public SearchResultsPageViewModel(
      INavigationService navigationService,
      IFlickrService flickrService,
      Func<SearchResultViewModel> resultViewModelFactory)
      this._navigationService = navigationService;
      this._flickrService = flickrService;
      this._resultViewModelFactory = resultViewModelFactory;

which I found neat but, no doubt, you’ve seen that sort of thing a thousand times Smile

This code doesn’t represent best practise in any way, shape or form (go get the Prism code and have a look at their sample) but it feels wrong to end the post without including the source code that I’m talking about so that’s downloadable from here if you want it.

Next steps – get as much of this back into my portable class libraries so that I can still get re-use across Windows 8/Windows Phone 8. How will that work with Prism when Prism isn’t portable?….

Prism for WinRT Applications–Sketchy Explorations

Following up on my previous post about Prism for WinRT applications, I thought I’d start digging in and trying to see what’s present in the Prism framework libraries.

I wasn’t entirely sure how to approach this. With the Prism bits you get three things;

  1. The Prism libraries for Windows Store applications
  2. A number of quick-start projects
  3. The AdventureWorks Shopper application

and then there’s also a bunch of documentation that you can either read online or download.

I thought about a few different ways that I could start to explore what was there. One thing I’d point out is that I have a bit of an aversion to samples so I tend to look at samples last rather than first and I know a lot of people work the other way around so bear in mind while you’re reading this that I have a particular way of going about these things and that these are really just my slightly scrappy notes as I try and poke around the new Prism framework and figure out what’s there for a Windows Store app.

If you want the definitive guide – read the definitive docs Smile

The Docs

I started with the docs. At the time of writing, I haven’t completely finished reading them but what I’d say from my first reading is;

  1. They are quite big at around 200 pages.
  2. They are surprisingly readable for a 200 page document.
  3. There’s a lot in there that is going to be useful to you whether you ever use the Prism framework or not. If you’re building a Windows Store app (or a Phone app) then I think these docs are still very much worth a read as they cover a lot of ground. Here’s some topics that I was not expecting to find in the Prism docs;
    1. “What is MVVM?”
    2. “Adding design time data”
    3. “Reading error messages from resource files”
    4. “Making key decisions about touch”
    5. “Handling suspend, resume”

and so on – it’s a long list of really useful and thought provoking topics for anyone who’s thinking about building an app.

As an aside, one of the things that I’m not overly keen on is seeing Prism describing itself as guidance for “Windows Store Business Applications”.

For me, I don’t really see the guidance as being anything specific to business applications. I see the guidance as being for writing good, structured, layered, maintainable applications. I don’t think those attributes should only be thought about in the context of business applications – they need to be applied to all applications that are going into the Windows Store and I’d almost say that they are more important for consumer applications because at least in a business you typically have a closer relationship with the end user whereas in a general Store, you need to make sure your app is solid from day one as your consumer isn’t likely to drop you an email if the app doesn’t meet their expectations.

Other than that, I think the docs are great and really deserve a proper read and I’ll finish my own reading of them in the coming days.

The Framework/Libraries

The next thing that I wanted to do was to have a poke around the libraries themselves. The package distributes;


and so I figured that I’d start off in the world of the pub-sub-events folder and then poke into the StoreApps folder and, from time to time if I get stuck, maybe I’d drop into the Quickstarts folder to see if that helped me figure things out.


The idea of the pub-sub events project is to promote loosely coupled events.

In .NET events are first class citizens of the languages like C# and VB but there’s a tight coupling between ClassA and ClassB if the former wants to handle an event raised by the latter – they need to know about each other from a typing perspective if they are going to achieve that. They also will need to know about whatever type represents the event data that’s passed from the source of the event to the sync of the event but that’s pretty much unavoidable.

As an aside, I’m reminded a little bit of the old notion of “connection points” in COM which had a form of loosely coupled events based around (being COM) interfaces rather than implementation types but that’s really “another story” so let’s leave that alone.

In Prism, there’s this notion of an EventAggregator which looks like this;


The fact that EventAggregator implements an interface means that a class can make use of it without taking a hard dependency on anything other than the interface type ( i.e. with no hard dependency on the implementation type EventAggregator itself ). It also means that it’s easy to register an event aggregator into some Inversion of Control (IoC) container and have it resolved dynamically to some type which implements IEventAggregator.

What does it do? It provides a dating agency for events.

Let’s say that I’m building an app which can be used anonymously but, equally, can be used by a logged on user and the decision as to whether to login or not might be up to the user and it might be possible for the user to login at any time during the lifetime of the application (perhaps it’s on the Settings charm in Windows 8).

When the user logs in, I might need to fire an event around the application to let “interested” components know that the user has logged in or logged out. Let’s say that the event payload looks like;

  public class LoginStatus
    public bool IsLoggedIn { get; set; }

    public string UserName 
        if (!this.IsLoggedIn)
          throw new InvalidOperationException("Not logged in");
        return (this._userName);
        this._userName = value;
    string _userName;

If I wanted one component to be able to “publish” an event of this “shape” and another component to be able to “subscribe” to an event of this “shape” then the only thing that I really want to share between those 2 components is the “shape” of the data class itself along perhaps with any common “pub/sub” infrastructure that I’m prepared to take a dependency on to get the job done ( in this case, that infrastructure is Prism PubSub Events ).

I’d need to create an EventAggregator somewhere;

      // Ok, so in this instance I know where my aggregator is coming from
      // because I'm creating it but let's pretend it's in a container.
      EventAggregator aggregator = new EventAggregator();

      // Let's treat the aggregator as though we don't know very much
      // about it.
      IEventAggregator abstractedAggregator = aggregator;

Now, assuming that I have some code that “knows” how to locate an IEventAggregator and that the code “knows” about the previously defined LoginStatus class I could define an event args class which will “carry” the LoginStatus event data;

  public class LoginStatusChangedEventArgs : PubSubEvent<LoginStatus>

and then I could publish an event;

      LoginStatus newLoginStatus = new LoginStatus()
        IsLoggedIn = true,
        UserName = "Mike"


and then some other component can subscribe to receive events of that particular shape – e.g.

      IEventAggregator abstractedAggregator = aggregator;

        loginStatus =>
          // Do something with the new login status.

Now, there are some bits in there which I left out and there are some additional nuances that the library does around this event publication/subscription functionality.

Firstly, what does PubSubEvent<T> look like? Putting that onto a class diagram really involved putting most of the rest of the pub sub library code onto a diagram;


In short – PubSubEvent<T> is a class that maintains a list of subscribers to an event of “shape” <T> and knows how to publish data of shape <T> to those subscribers. It has some additional smarts though which can best perhaps be seen by looking for all the overloads of the Subscribe() method;


We can subscribe to an event of a particular shape but we can also specify on which thread we’d like that subscription delivered;

  1. Dispatched on whatever thread the publisher calls the Publish() method from.
  2. Dispatched to the synchronization context represented by the SynchronizationContext property on the EventBase base class – this would usually mean “the UI thread” but it could be any arbitrary synchronization context.
  3. Dispatched from the .NET thread pool.

and we can also specify a filter (Predicate<T>) to filter when we’d like the event subscriptions delivered to our subscriber. For instance – in my example I might only want events delivered if the user was logged in or logged out.

Finally, there are some smarts here around garbage collection – that is, if objectA makes a subscription to an event then should that subscription keep objectA alive in the absence of any other references to objectA or should objectA get garbage collected?

If you look at the class diagram, this is where IDelegateReference and DelegateReference come in – these are being used to keep weak references (where requested) to the delegates provided for any filtering and for the subscription itself.

I think this is an important topic because in MVVM applications you might often want to use this form of loose-event communication to get a piece of data from ViewModelA to ViewModel B. However, it’s often the case that two otherwise unrelated view models would have mutually exclusive lifetimes and so this idea of which components are “alive” and when they are “alive” becomes important.

Subscribing returns a SubscriptionToken and that is needed to be kept for a call to Unsubscribe (subject to all I’ve just said about weak references Smile) and disposing of a SubscriptionToken looks to be equivalent to passing it to the Unsubscribe() method.

One last things about the pub-sub library – it is portable so you can build code into a portable class library that makes reference to this code and then use that library from any .NET (4+), Silverlight (4+), Windows Phone (7.1+) or Windows Store application.


As you might expect, there’s quite a lot more in the Prism.StoreApps project than there is in the pub/sub events project. One of the things that occurs to me first when looking at this code is that it perhaps could be re-factored to extract it out into more than one library because some of the code in here is not specific to building a Windows Store application and so might gain from being packaged as a separate library to get some re-use from other kinds of app projects (e.g. Windows Phone).

The DelegateCommand Class

An example of that would be this DelegateCommand class;


This is a class which takes a couple of delegates and puts an ICommand interace on top of them.

Everyone in the MVVM world needs this kind of class and most people have written it once or twice themselves and it really belongs in the .NET framework but it’s good that it’s here in this library. That said, I’d argue that this is not specific to building Windows Store apps – it’s applicable in Windows Phone, WPF and Silverlight apps too so could maybe be packaged separately.

Regardless, while we’re looking at it – it’s a simple way to make a command on a view model. So, if you have some view model;

  public class MyViewModel  
    DelegateCommand _someCommand;

    public MyViewModel()
      _someCommand = new DelegateCommand(
    void OnSomeCommand()
    bool OnCanExecuteSomeCommand()
      return (true);

then you can use DelegateCommand to provide an ICommand implementation for you over the top of one or two delegates ( one for execution, one for “can execute” ) and there’s a method there for raising the CanExecuteChanged event of ICommand. It’s worth saying that you can omit the “can execute” delegate and the class defaults to returning true to signify “Yes, I can execute”.

The ViewModel Class

The MyViewModel class I just wrote wouldn’t get me very far – it’s well understood that it needs to implement INotifyPropertyChanged so there’s a base class in the Prism framework that gives me an implementation of that interface – it’s called BindableBase;


and anyone who’s looked at the Windows Store templates in Visual Studio 2012 will be familiar with BindableBase and will know that it implements INotifyPropertyChanged for you and will (like me) be scratching their heads as to why this still isn’t in the .NET framework around 8 years after we first started to need an implementation of INotifyPropertyChanged. Anyway, it’s here in this library so that’s a good thing.

Looking a little further, it’s clear that the Prism ViewModel base class does more for us than just INPC. It also provides two other pieces of functionality;

  1. It implements INavigationAware such that if an app has a Page1/ViewModel1 which drives a navigation to Page2/ViewModel2 and possibly passes a parameter as part of that navigation then it’s possible for the ViewModel2 to pick up that parameter and do something with it. Anyone who’s been along to my recent Windows Phone sessions will have seen me build an interface and implementation a little like this to solve this exact same problem so it’s nice to see something like this here in Prism. Without something like it, it can be a bit tricky to have a view model get access to navigation parameters from the built-in navigation service which is somewhat tied to the UI classes.
  2. It has a notion of a state dictionary – this is for the app lifecycle management situations in a Windows Store application where we need to suspend an app and save its state away which potentially means saving the state of views, view models and services. This is how Prism builds support for the view model being able to plug-in to that requirement.

It turns out that these things work together. Having a look at those two methods;


If we accept that there’s some componentry somewhere which can hook into Windows 8 Suspend/Resume and navigation such that;

  1. when we are suspending the app that componentry can call a ViewModel’s OnNavigatedFrom method and ask it to populate a state dictionary which can then be persisted along with the navigation history (depending on the navigation mode).
  2. when we come back to an app in the case where the app was terminated by Windows that componentry can restore the navigation history, restore the view and the ViewModel and then pass into the OnNavigatedTo method the stored dictionary

then this can be used to suspend/resume ViewModels. The base ViewModel class already does this in that it looks for any properties on the ViewModel which have a custom attribute applied to them;


and it automatically grabs their values and stores them into the dictionary. Where this dictionary is stored is a mystery at this point in my exploration but I’m sure it’ll become clear later on Smile

The ViewModelLocator Class

One of the pain points in MVVM is always in trying to decide the Chicken/Egg situation between a View and its ViewModel and how they get instantiated and learn about each other ( by which I mean the ViewModel becomes the DataContext of the View ).

The Prism library has a ViewModelLocator class to help with this. It’s pretty simple to understand but that’s not to say that it’s not useful or powerful. Here it is;


and it’s probably not immediately obvious from that picture that it brings with it a an attached property called AutoWireViewModel. What that means is that I can author a view in an app like this;


and the presence of that AutoWireViewModel property is going to cause the ViewModelLocator class to attempt to “magically” set the DataContext of this view for me. How does it do that?

  1. The class maintains a list of factories. It’s a simple mapping from a type name (the type name of the view) to a factory function which is used to create the ViewModel. That list of factories can be appended to using the Register method.
  2. If the factories list doesn’t know how to produce the view in question then;
    1. The defaultViewTypeToViewModelTypeResolver is used to try to map from the Type of the view to the Type of the ViewModel.
      1. This resolver can be overridden by calling the SetDefaultViewTypeToViewModelTypeResolver method.
      2. Without any overriding, the class will essentially try to take the name of the View type and manipulate the namespace to change “Views” into “ViewModels” and “View” into “ViewModel”. This would mean that if you have a Views folder in your project with classes ending in …View then they would be matched up with classes ending in …ViewModel in a corresponding ViewModels folder.
    2. The defaultViewModelFactory is used to try and create the ViewModel.
      1. This factory can be overridden by calling the SetDefaultViewModelFactory method.
      2. Without any overriding, the class will try to use Activator.CreateInstance() to create the ViewModel.

This is all nicely lined up to allow for dependency injection. At application start-up time it’s easy to grab hold of the ViewModelLocator and call its SetDefault…X methods to pass in functions which can delegate the work of creating ViewModels to a IoC container.


Navigation can be a bit of a struggle in an MVVM app. The main problem is that navigation is performed by a Frame which is a UI construct and we don’t usually have reference to UI constructs in a ViewModel which means that we usually need to have some abstraction of a navigation service which make the services of the Frame available from within a ViewModel without exposing the details of the Frame itself to the ViewModel.

The other struggle with navigation is that it works differently on Windows 8 to how it works on Windows Phone 8 which means that a developer wanting to target both with a single codebase has to do some more abstraction work.

The Prism libraries have abstracted a navigation service. The essence of this is the INavigationService interface;


where the Navigate method has moved towards a hybrid of the Windows 8 style implementation where you navigate to a Type of page and pass a parameter of type object and the Windows Phone implementation where you navigate to a URI with the parameter embedded within it.

The Navigate() method looks like;


so you’re navigating based on some string plus an object parameter and that string can then be mapped onto some actual view type at a later point.

A ViewModel (or some other component) can then take a dependency on INavigationService and an implementation of the service could be injected. In the framework, there’s an implementation called FrameNavigationService;


Initially, I’d have perhaps expected the FrameNavigationService to make direct use of a Frame but, instead, it further abstracts its dependence on a Frame by hiding it behind IFrameFacade. That interface (which has interesting GetValue/SetValue methods on it like it was derived from DependencyObject) is then implemented by another class FrameFacadeAdapter which implements it on top of an actual (Windows 8) Frame;


The FrameNavigationService needs an IFrameFacade to work but it also depends on two other bits of functionality;


One is a function that knows how to resolve a string parameter into a Type. When the navigation service is asked to Navigate(“foo”) it can pass that string through the navigationResolver in order to map from the string name to an actual view type.

The other service that’s required by the FrameNavigationService is the ISessionStateService;


The provided implementation of this session state service (SessionStateService) firstly has a Dictionary<string,object> called SessionState which is publicly accessible can be used to store the objects that represent global state and the methods SaveAsync() and RestoreSessionStateAsync() will write/read that dictionary into a file in much the same way as the SessionStateManager class from the Visual Studio templates does (possibly with the addition of encrypted data).

In order to save those objects stored in the state dictionary, they will need to be serializable with the DataContract serializer and any additional types that the serializer needs to know about need to be registered via the RegisterKnownType() method.

The other thing that the class does is to manage a set of frames (represented by IFrameFacade here) although most apps will perhaps have a single frame. Frames (IFrameFacades) can be registered with the service via the RegisterFrame(IFrameFacade facade, string sessionStateKey) method.

Registration stores the session key passed with the IFrameFacade on the IFrameFacade itself (via the SetValue method) and stores a weak reference to the IFrameFacade in a list held by the SessionStateService.

Essentially, in combination with the GetSessionStateForFrame(IFrameFacade) method, a slot in the SessionState is reserved for the frame using the session state key for that IFrameFacade. That slot stores another Dictionary<string,object> specifically for the frame. A weak reference to the frame is also stored in a list inside of the SessionStateService.

So, we end up with a Dictionary<string,object> where some of the entries are more Dictionary<string,object> for any frames that have registered a key to store their state.

When the state service is saving state, it walks its list of IFrameFacades and makes sure that each one records its current navigation state into its own dictionary and then the service writes the whole “master” dictionary to a file.

The FrameNavigationService ties all these things together. Most of its “work” is delegated down to the IFrameFacade (which in turn delegates down to the Frame) so for simple things like;

  1. GoBack()
  2. CanGoBack()
  3. ClearHistory()

not much happens.

When it comes time to Navigate(), the service uses the navigationResolver to translate the string that has been passed to Navigate() into a Type parameter before asking the underlying IFrameFacade to actually Navigate() which, in turn, will ask the underlying Frame to Navigate().

Finally, the service effectively adds the “idea” of navigation support to ViewModels.

The service attaches event handlers to the IFrameFacade’s Navigating and Navigated events such that whenever navigation occurs, the IFrameFacade is interrogated to see if it contains Content and if that content is a FrameworkElement then that can be used to obtain a DataContext and, finally, if that object living in the DataContext implements INavigationAware then that provides a means via which the ViewModel can be notified as the app is navigating to/from the page that is loading that ViewModel.

This is done via INavigationAware.OnNavigatingTo and INavigationAware.OnNavigatingFrom and it’s a means via which the ViewModel can;

  1. Pick up the navigation parameter.
  2. Pick up the navigation mode.
  3. Save/Restore state for itself.

The FrameNavigationService also makes sure that if the app suspends or wakes from a termination then the navigation history is put back in place on the frame( s ) and the relevant ViewModel is driven to save/restore state by driving it through this OnNavigatingTo/OnNavigatingFrom logic.

The VisualStateAwarePage Class

The VisualStateAwarePage is the Page-derived base class for your pages and feels pretty similar to the LayoutAwarePage that comes with the Visual Studio templates (you get that page if you add a Basic Page project item to a Windows Store project).

The page does a number of things;

  1. Watches for view/orientation changes and drives the UI into different visual states depending on those changes. The state names used are taken directly from the ApplicationViewState enum and so will end up being called “FullScreenLandscape”, “Filled”, “Snapped”, “FullScreenPortrait”. These state changes are handled for the page itself along with any controls on the page that have been registered as being “interested” in visual state changes via the StartLayoutUpdates method.
  2. Implements state management for the page (i.e. the View rather than the ViewModel) by providing virtual methods LoadState and SaveState which are passed Dictionary<string,object> for you to save/restore your view’s state.
  3. Provides some convenience methods for forward/back/home navigation and for trapping mouse/keyboard/touch gestures to trigger them.

and that’s pretty much it for the VisualStateAwarePage except that it does one other slightly “odd” (to me) thing. There’s a public static property on this class called GetSessionStateForFrame and that property is of type Func<IFrameFacade, IDictionary<string,object>>.

This is part of (2) above – the state management of the view.

When the page is navigated to or navigated from and wants to restore/save state it needs somewhere to put that state. What it does is to;

  • create a new FrameFacadeAdapter around its Frame (which is has access to because it’s a view which is Page derived).
  • call whatever function is present in the GetSessionStateForFrame property passing it the FrameFacadeAdapter in the hope that it will return an IDictionary<string,object>
  • reach into that dictionary returned, using a page-specific key to attempt to pull out another Dictionary<string,object> which can be used as state storage for the page

    I must admit that I found this functionality a bit “opaque” and it felt a little to me like there’s a missing interface somewhere – it took quite a bit of staring at to try and figure out what’s going on.

    The MvvmAppBase Class

    The MvvmAppBase class is the class that brings all the other pieces together for your app and replaces the standard Application class that provides the base class in the framework and in the standard Visual Studio templates. It derives itself from that Application class and, in my view, simplifies some of the rough edges of that class for you.

    It does quite a lot of work on your behalf and provides lots and lots of places to hook into the default behaviour by overriding methods.

    The starting point for this behaviour is in the override of the OnLaunched method for when the application first runs up. This initialises the root frame which involves a lot of functionality;

    1. Creating the Frame.
    2. Creating a FrameFacadeAdapter to implement IFrameFacade on top of that Frame.
    3. Creating the SessionStateService to provide an implementation of ISessionStateService and storing this in a protected property (SessionStateService of type ISessionStateService) of the MvvmAppBase class itself and registers the main Frame with that service.
    4. Creating the INavigationService by calling a virtual method CreateNavigationService and passing it the IFrameFacade and the ISessionStateService. This is stored in a protected property NavigationService on the MvvmAppBase class itself.
    5. Wires up the static property VisualStateAwarePage such that it has a method to call in order to get the Dictionary<string,object> session storage for a particular frame.
    6. Wires up the SettingsPane such that when it requires settings information for your app it will effectively call the classes own virtual method called GetSettingsCharmActionItems() which you can implement to return your settings options.
    7. Wires up the ViewModelLocator so that, by default, it will call a virtual function Resolve on the MvvmAppBase class in order to create view models.
    8. Calls a virtual method to OnRegisterKnownTypesForSerialization() in case you have any to register with the ISessionStateService.
    9. Sets up handlers for the suspend/resume/terminate state management pieces (and implements those handlers).
    10. Calls a virtual OnInitialize() method via which you can initialise your app’s code.

    That’s quite a lot and you’d need a few overrides in order to get this wired up to look to a container for resolution of these types. Once the application is actually up and running the class also;

    1. Checks the application manifest and if the Search charm is declared there then it grabs hold of the SearchPane and, effectively, wires up the submission of a search query to its own OnSearchApplication virtual method for you to override.

    It’s worth pointing out that the class also overrides the base class OnSearchActivated such that it initialises things and then calls the same OnSearchApplication virtual method thereby giving you one place to implement that functionality.

    Finally, the Suspending event is wired to an OnSuspending handler which will do the right thing around the NavigationService and the SessionService ( using the properties on this class to get hold of those values ) and will also set a simple IsSuspending flag while the operation is in flight.

    Wrapping Up

    At a sketchy level, that’s perhaps most of the classes that Prism provides. I’ve not touched on some of the other services like the ability to display flyouts but that’s my first encounter with the source code. I’ve also not poked so far into the reference application.

    What I think I’d want to do next is build my own “Hello World” using an IoC container like Unity or AutoFac and see how that goes.

    Of course, there’s already a sample in the QuickStarts which does exactly this but I figure I’ll learn more by experimenting with it for myself…