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

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


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.


As an amalgam of Goran's accepted answer and Rene's excellent comment.

  • Add the namespace declaration.xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

  • Reference your design time data context from code.
    <Grid d:DataContext="{d:DesignInstance Type=ViewModels:MockXViewModel, IsDesignTimeCreatable=True}" ...


I use this approach for generating design time data with .NET 4.5 and Visual Studio 2013.

I have just one ViewModel.The view model has a property IsInDesignMode which tells whether design mode is active or not (see class ViewModelBase).Then you can set up your design time data (like filling an items control) in the view models constructor.

Besides, I would not load real data in the view models constructor, this may lead to issues at runtime, but setting up data for design time should not be a problem.

public abstract class ViewModelBase{    public bool IsInDesignMode    {        get        {            return DesignerProperties.GetIsInDesignMode(new DependencyObject());        }    }}public class ExampleViewModel : ViewModelBase{    public ExampleViewModel()    {        if (IsInDesignMode == true)        {            LoadDesignTimeData();        }    }    private void LoadDesignTimeData()    {        // Load design time data here    }       }