How to use a DesignInstance to populate controls with design time data in Silverlight and WPF

In this post I’ll be showing how you can use a DesignInstance to populate controls when you’re designing Silverlight or WPF applications in Expression Blend or Visual Studio.

The image below shows a user control in Expression Blend which allows users take part in a poll to find out what their favorite colors of the rainbow are.

Expression Blend Without Design Time Data

As you can see it’s difficult if not impossible to imagine what we are actually designing here.

The user control doesn’t look any better in Visual Studio 2010.

Visual Studio  WithoutDesign Time Data

Creating the ViewModel to bind the data context using DesignInstance

The code below shows the DesignTimeViewModel class to be used as the data context during design time. It inherits from the ViewModel class which will be used when the application is actually running.

public class DesignTimeViewModel : ViewModel
{
    public DesignTimeViewModel()
    {
        Name = "Roy G Biv";
        RainbowColors = new ObservableCollection<RainbowColor>()
                            {                                    
                                new RainbowColor() {Description = "Red", Color =  "#FFFF0000"},
                                new RainbowColor() {Description = "Orange", Color =  "#FFFFA500"},
                                new RainbowColor() {Description = "Yellow", Color =  "#FFFFFF00"},
                                new RainbowColor() {Description = "Green", Color =  "#FF008000"},
                                new RainbowColor() {Description = "Blue", Color =  "#FF0000FF"},
                                new RainbowColor() {Description = "Indigo", Color =  "#FF4B0082"},
                                new RainbowColor() {Description = "Violet", Color =  "#FFEE82EE"}                                    
                            };
    }
}

public class ViewModel : INotifyPropertyChanged
{
    private string _name;

    public event PropertyChangedEventHandler PropertyChanged;

    public string Name
    {
        get { return _name; }
        set
        {
            _name = value;
            OnPropertyChanged("Name");
        }
    }

    public ObservableCollection<RainbowColor> RainbowColors { get; set; }

    protected void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this,
                new PropertyChangedEventArgs(propertyName));
        }
    }
}

public class RainbowColor
{
    public string Description { get; set; }
    public string Color { get; set; }
}

Setting the DataContext to use DesignInstance in XAML

In order to bind the DesignTimeViewModel to the user control during design time we need to add a few more lines in the opening tag.

The lines that use a DesignInstance to bind data in the designer are highlighted in the XAML for the user control below.

 <UserControl
	xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
	xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
	x:Class="DeginTimeDataInSilverlightApplications.MainPage"
	xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
	mc:Ignorable="d"
	xmlns:d="http://schemas.microsoft.com/expression/blend/2008"            
	xmlns:local="clr-namespace:DeginTimeDataInSilverlightApplications"
    d:DataContext="{d:DesignInstance Type=local:DesignTimeViewModel,IsDesignTimeCreatable=True}"
    d:DesignWidth="600">
    <UserControl.Resources>
        <DataTemplate x:Key="RainbowTemplate">
            <Border Background="{Binding Color}">
                <StackPanel Margin="10" Orientation="Horizontal">
                    <CheckBox/>
                    <TextBlock Text="{Binding Description}" 
                               Foreground="Black" 
                               FontWeight="Bold" />
                </StackPanel>
            </Border>
        </DataTemplate>
        <Style x:Key="ListBoxStretchStyle" TargetType="ListBoxItem">
            <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
        </Style>
    </UserControl.Resources>
    <Grid x:Name="LayoutRoot" Background="White">
        <StackPanel>
            <TextBlock Text="Choose your favorite colors!" 
                       Margin="5" 
                       TextAlignment="Center"
                       FontWeight="Bold" />
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto"/>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="Auto"/>
                </Grid.ColumnDefinitions>
                <TextBlock Text="Name:" Margin="10" VerticalAlignment="Center" />
                <TextBox Text="{Binding Name}"  Grid.Column="1"  VerticalAlignment="Center"/>
                <Button Content="Submit" Grid.Column="2" Margin="10"  Width="100" Height="50"/>
            </Grid>
            <ListBox ItemsSource="{Binding RainbowColors}" 
					 ItemContainerStyle="{StaticResource ListBoxStretchStyle}" 
					 ItemTemplate="{StaticResource RainbowTemplate}"/>
        </StackPanel>
    </Grid>
</UserControl>

Pay attention to the line

mc:Ignorable="d"

If you don’t add this you will see the following error when you try to compile the solution

XAML Namespace http://schemas.microsoft.com/expression/blend/2008 is not resolved.

If you’re using Expression Blend the designer will now look like this

Expression Blend With Design Time Data

or like this if you’re using Visual Studio 2010

Visual Studio With Design Time Data

Does it matter if I’m using MVVM or not?

No. Even though I’m using a ViewModel in this example, all that matters is that you can bind your sample data to the data context of the control.

Comments

  • http://gui-at.blogspot.com Lukas

    Thanks for this simple idea.

  • http://twitter.com/Infinitecodex Jason Short

    You just saved me such a headache I have been having with layout. 
    One little tweak I did on your design was to actually have the Designtime class just call my mock service layer to generate the data for me.  Works like a charm.

  • Braincube

    Thanks. You save my day!