WPF: How can I create sample data in design mode?

jbe picture jbe · May 4, 2010 · Viewed 9k times · Source

I would like to create sample data which are created only in design mode (When the WPF Window is shown in the Visual Studio WPF Designer or in Expression Blend). I tried this:

public MainWindow()
{
    InitializeComponent();

    if (DesignerProperties.GetIsInDesignMode(this))
    {
        DataContext = new Person() { Name = "Harry" };
    }
}

It seems that the designer doesn't call the constructor of the Window class. I need to create the sample data in C# code because they are more complicated to instantiate. Any ideas?

Answer

John Bowen picture John Bowen · May 4, 2010

If you do the setting of the DataContext in XAML, either directly or with a Binding, you avoid the issue of constructor skipping. The newer versions of the tools also support setting a d:DataContext that will only be invoked at design time to set the DataContext. If your instantiation can't be done directly in XAML (i.e. constructor parameters) you can just declare a get property in MainWindow.xaml.cs to instantiate and return your design data instance. Keeping the entire object creation in the getter will keep it from being created at run-time because it will never be called.

public MyData { get { return new Person() { Name = "Harry" }; } }

Then in XAML you can bind d:DataContext for the window to the new property.

d:DataContext="{Binding RelativeSource={RelativeSource Self}, Path=MyData}"

There are many other options for doing this but this is the closest to the UI so usually the easiest to add into existing code. Josh Smith recently did a good overview of different options: Design-time data is still data