Tuesday, December 07, 2010

The simplest way to do design-time ViewModels with MVVM and Blend.

The problem is this: You’ve created your Views and ViewModels, but when you view them in Blend, you either see nothing, or the data you see is not useful for testing what you want in the view. There are various ways to deal with this, including writing code (either in the ViewModel or in a service locator) to return different data at design time.
I’m going to demonstrate a different way that doesn’t involve code, and is very simple and most importantly: Malleable.

Assumptions/Prep:

  • I have a ViewModel class called “BooksViewModel” that supports the search UI and result-set. This has some non-trivial properties such as a collection of “Book” classes.
  • I have a View called “BooksView” that allows you to search for books, but I haven’t yet hooked up the data bindings (it’s easier to do after you create sample data).
  • I have no code to differentiate between design time and runtime. The code is geared purely towards runtime.

What we’ll do:
  • Use Blend to create some purely fake sample data.
  • Assign the fake data as the data-context of the control you want, in a design-time-only fashion.
  • Create the bindings and play with the data.
Step 1: Create some fake data with Blend:
Go to the “Data” tab, and create sample data from a class: