2011-08-22

Run-time and design-time selection of a ViewModel using XAML

I've been working on a WPF project in Visual Studio 2010 and I came across a problem where Visual Studio would crash when I used the Document Outline while editing an XAML in the Design view. There seems to be several ways of solving this but all the methods seem to involve code either as a separate class such as a ViewModelLocator or in a code-behind using GetIsInDesignMode.

Here is a solution that uses (mostly) XAML. First, create a new ViewModel class that is a stub or mock. This class will also allow you to have some design-time data that won't crash Visual Studio. Then implement the following XAML to select between your main ViewModel and your mock ViewModel. The Blend XML Namespace ("d") is marked as Ignorable (only available during design-time) then AlternateContent is used to select the MockViewModel if the "d" namespace is available (design-time) and fallback to the MainViewModel (run-time).

1 comment:

Unknown said...

Interesting, could we use this to have a single XAML for WPF and Silverlight somehow?

PreferenceKey Quirks

PreferenceKey has a few quirks that have tripped me up. One is the reduce(value:nextValue:) implementation. The other is that a PreferenceKe...