views:

283

answers:

2

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?

+2  A: 

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

John Bowen
Thanks for your answer – your solution looks really great. Unfortunately, I tried it with VS2010 but it didn’t work. Does this Binding really work for d:DataContext?
jbe
A: 

Now I’m using the design-time support of Visual Studio 2010 and Expression Blend 4. This new feature meets most of my requirements.

How this works is shown in the BookLibrary sample application of the WPF Application Framework (WAF). Please download the .Net4 version of WAF.

jbe