Category Archives: Unity

Windows Store Apps with Prism and Unity

It’s been mighty quiet around here. Sorry about that, I’ve been up to my neck in a new project that’s been keeping me pretty busy.

I am going to start a mini-series on developing Windows Store apps using Prism and Unity.

The first of the series (in other words, this post) will look at how to separate your UI and ViewModels into separate projects, but more specifically, how to override the default behaviour to look up the view models from the appropriate place.

By default, Prism will look for your views in the “Views” folder, and take the name of the view (e.g. MainPage.xaml) and use that to look for the ViewModel in the same project’s ViewModels folder. The basics of what it does are to remove the “Page” part from the end of the class name, replace it with ViewModel and look up the class in the x.ViewModels namespace. Of course, if you want to put your ViewModels in another project for maintainability purposes, you’ll need to do a bit of dancing to get it to work.

Thankfully, it’s pretty simple. In your main UI project’s App.xaml.cs, locate the OnInitialise method and add the following code.

Basically, we get the fully qualified name of the target assembly and class type, turn that into a type, and then return it to the view model locator. In the example above, my main UI project is called “MyProject.UI”, and my UI logic (with the view models) is contained in “MyProject.UILogic”.

One thing to notice from my code is that it will also account for namespaced folders beneath the Views folder. The default example implementations don’t take this into account, so the view “Views\Flyouts\AboutPage.xaml” wouldn’t resolve the ViewModel if you follow the same folder structure in the ViewModels folder. Don’t worry, though – as long as you create the same sub-folder structure and have your ViewModels in the correct location, the code above will work.

Don’t forget, though, you’ll need to manage the strings in the snippet above so that they match your assemblies’ fully qualified names. I’ll leave that as an exercise for you, though.