Using ViewModels to inject Design-Time data

To make your apps design more tangible when using Blend or Visual Studio we often resort to injecting design-time data in some kind of way.

One of the best ways to do it to actually fake the entire ViewModel and have one that’s used at design-time.
I tried this approach on a new app that I’m also using MVVM Light in. And I couldn’t get it to work at first, I kept getting the error: The name “DesignTimeViewModel” does not exist in the namespace “clr-namespace:MyNamespace.ViewModel”.

How to bind a Design-Time ViewModel to the XAML View

For those that do not know, here’s how you bind a desing-time viewmodel to your views. You need to declare a namespace where your view exists, a reference to http://schemas.microsoft.com/expression/blend/2008 and point out a DesignInstance DataContext. Add the following code in the PhoneApplicationPage-tag:

    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:designTimeViewModel="clr-namespace:MyNamespace.ViewModel"
    mc:Ignorable="d"
    d:DataContext="{d:DesignInstance Type=designTimeViewModel:DesignTimeViewModel, IsDesignTimeCreatable=True}"

With MyNamespace.ViewModel being the namespace your viewmodel is located in and DesignTimeViewModel being the name of your viewmodel.

The way I created my design-time viewmodel was by just copying the regular viewmodel, adding a parameterless constructor and adding data to the properties in that constructor.

The solution

With me using MVVM Light all the viewmodels I ha dimplemented was inheriting from GalaSoft.MvvmLight.ViewModelBase, when copying the viewmodels to create my design-time viewmodels I din’t remove the inheritance. And it turns out that this inheritance was the root of the problem.

So if you remove the inheritance from GalaSoft.MvvmLight.ViewModelBase on your design-time viewmodels the error should disappear.

Happy coding!

MVVM Light on Windows Phone 8 & Design-Time ViewModels
Tagged on:     

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.