Tuesday, March 22, 2011


Sharing a ViewModel in MVVM

This method of ViewModel reuse is an evolution, after further learning, of the first attempt (http://feddas.blogspot.com/2010/12/reusing-viewmodel-in-mvvm-for-wp7.html). In contrast to the linked method, this one offers kinder integration with the Visual Studio IDE at the cost of the ViewModel code needing to be recompiled for every View.
  1. Install MVVM Light V3 Binaries and Templates for your flavor of Visual Studio

  2. Install the WP7 RTM hotfix

  3. If you did not unblock the MVVM binaries .Zip file before you installed you can either unblock that .Zip file now and reinstall (the recommend method) or individually unblock all of the installed MVVM Light binaries for WP7 and Silverlight 3.

    Location of the to Unblock button in a files properties

  4. Create a new MvvmLight (WP7) solution with any name, in the example I named it "VMresue".

    Creating a new WP7 MVVM Light solution

  5. Add a second project (File/Add/New Project...) WP7 or Silverlight. If you're creating a Silverlight project ensure that it's using Version 3 as this version is more compatable with WP7.

    Adding an MVVM Light Silverlight 3 Project

  6. Delete the contents of the "ViewModel" folder in the new project. Replace them with links to the VM of the first project. If you did it correctly you will have small "shortcut" arrow in the lower left for the linked files in the Solution Explorer.

    Adding a Link to existing files

  7. Adjust new projects to reference the same namespace as the first project. This requires changing App.xaml.cs's using line from "using VMinSilverlight.ViewModel;" to "using VMreuse.ViewModel;".
Using this method, code from a single location can be used for all of your projects. This enables expressing a ViewModel in a range of completely different and isolated Views.

Labels: , ,

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]