What approaches are available to dummy design-time data in WPF?

el2iot2 picture el2iot2 · Dec 11, 2009 · Viewed 37k times · Source

I am working without expression blend and just using the XAML editor in vs2010. The wisdom of this aside, I am increasingly seeing a need for design-time data binding. For simple cases, the FallbackValue property works very nicely (Textboxes and TextBlocks, etc). But especially when dealing with ItemsControl and the like, one really needs sample data to be visible in the designer so that you can adjust and tweak controls and data templates without having to run the executable.

I know that ObjectDataProvider allows for binding to a type, and thus can provide design-time data for visualizing, but then there is some juggling to allow for the real, run-time data to bind without wasting resources by loading loading both the design time, dummied data and the runtime bindings.

Really what I am wanting is the ability to have, say, "John", "Paul", "George", and "Ringo" show up in the XAML designer as stylable items in my ItemsControl, but have real data show up when the application runs.

I also know that Blend allows for some fancy attributes that define design time binding data that are effectively ignored by WPF in run-time conditions.

So my questions are:

1. How might I leverage design-time bindings of collections and non-trivial data in the visual studio XAML designer and then swap to runtime bindings smoothly?

2. How have others solved this design-time vs. runtime data problem? In my case, i cannot very easily use the same data for both (as one would be able to with, say, a database query).

3. Are their alternatives to expression blend that i could use for data-integrated XAML design? (I know there are some alternatives, but I specifically want something I can use and see bound sample data, etc?)

Answer

Goran picture Goran · Mar 20, 2011

Using VS2010 you can use Design-Time attributes (works for both SL and WPF). I usually have a mock data-source anyway so it's just a matter of:

  • Adding the namespace declaration

    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    
  • Adding the mock data context to window/control resources

    <UserControl.Resources>
      <ViewModels:MockXViewModel x:Key="DesignViewModel"/>
    </UserControl.Resources>
    
  • Setting design-time data context

    <Grid d:DataContext="{Binding Source={StaticResource DesignViewModel}}" ...
    

Works well enough.