WPF Design-time Data With MVVM

One of the best things about WPF is the ability to view and modify your (mostly) running program in the designer (Expression Blend or the designer built in to Visual Studio). Unfortunately, design-time data only really became easy to use with .NET 4.0 and still remains strangely under documented.

My goal with design-time data is use the same ViewModels as my running application but with sample data coming from specially dummy models. This greatly reduces the number of edit/compile/test cycles that plague WPF development and its run-time binding errors.

First, create a dummy implementation of the model/service layer that provides the fake data and prevents the designer from attempting to connect directly to the database:

DesignTimeDatabaseLoader : IDatabaseLoader
    public IEnumerable<ShoppingCartItem>(User user)
        yield return new ShoppingCartItem( "Soap", "soap.jpg", 2 );
        yield return new ShoppingCartItem( "Cereal", "cereal.jpg", 1 );

Next, create a sub-class of the ViewModel:

public class ShoppingCartViewModel : ViewModelBase
    private readonly IDatabaseLoader m_Loader;
    private readonly List<ShoppingCartItem> m_CartItems = new List<ShoppingCartItem>();
    public ShoppingCartViewModel(IDatabaseLoader loader)
        m_Loader = loader;
        m_CartItems.AddRange(loader.LoadShoppingCartItems( User.GetLoggedinUser() ));
    public IList<ShoppingCartItem> CartItems { get { return m_CartItems; } }

public class DesignTimeShoppingCartViewModel : ShoppingCartViewModel
    public DesignTimeShoppingCartViewModel()
        : base( new DesignTimeDatabaseLoader() )

Then, modify the view’s XAML to use the design-time view model as the data context only when running inside of the designer using the d:DataContext attached property:

<Grid d:DataContext="{d:DesignInstance ViewModels:DesignTimeShoppingCartViewModel, IsDesignTimeCreatable=True}">
    <ItemsControl ItemsSource="{Binding CartItems}"
                  ItemTemplate="{StaticResource ShoppingCardItemDataTemplate}" />

Now, you will be able to view the sample items in the designer. This allows you do make changes to the XAML and see the results immediately. This also allows you to edit the item templates of ItemsControls directly in the collection. In Blend, right-click on the ItemsControl and choose Edit Additional Templates->Edit Generated Items.

I’ve found the design-time view models to be oddly fragile. Any exceptions or configuration errors tend to either be silently suppressed by Blend or Visual Studio or to simply cause the entire designer to crash. I’d suggest creating unit-tests that create new instances of the design-time ViewModels. It’s much, much easier to debug and diagnose errors that way.

Further reading: