Design-Time Data Binding in WPF

One of the cool things that WPF allows you to do is create sample data that can be bound to controls at design-time. This spiffy little feature allows you to do all kinds of tinkering with your UI without having to run your application. A short feedback loop is essential since WPF provides so much flexibility with what you can do. If you have an application that loads a significant amount of data, and you need to load all that data each time you want to see a UI change, that can lead to a significant amount of wasted time.

When you search for how to do this on the web, the most common method is to create a XAML file with your sample data, and then reference the file in the design data context. Here’s a very short example.

Spartan.cs

namespace adamprescott.net.DesignTimeDataBinding
{
    public class Spartan
    {
        public string Profession { get; set; }
        public byte[] Picture { get; set; }
    }
}

SpartanSampleData.xaml (Be sure to change BuildAction to DesignData!)

<m:Spartan xmlns:m="clr-namespace:adamprescott.net.DesignTimeDataBinding" 
           Profession="HooHooHoo">
</m:Spartan>

MainWindow.xaml

<Window x:Class="adamprescott.net.DesignTimeDataBinding.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        d:DataContext="{d:DesignData Source=/SpartanSampleData.xaml}"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <DockPanel VerticalAlignment="Top">
            <Image Source="{Binding Picture}" Height="50" />
            <TextBlock Text="{Binding Profession}" />
        </DockPanel>
    </Grid>
</Window>

I had a problem with this method, though. My model had a byte array property that stored image data, and I couldn’t come up with a good way to include a sample image in the design data XAML. I learned that you can also accomplish design-time data binding through the use of static classes, and that gave me exactly what I was looking for: the ability to create and define sample data in code! Here’s the same example as above, modified to use a static class.

SpartanSampleDataContext.cs (Note that I also added an image to the project in the root namespace.)

namespace adamprescott.net.DesignTimeDataBinding
{
    using System;
    using System.IO;
    using System.Reflection;
    using System.Windows;

    public static class SpartanSampleDataContext
    {
        public static Spartan SpartanSampleData
        {
            get
            {
                var result = new Spartan
                {
                    Profession = "HooHooHoo",
                    Picture = GetSampleImageBytes()
                };
                return result;
            }
        }

        private static byte[] GetSampleImageBytes()
        {
            var assemblyName = new AssemblyName(
                Assembly.GetExecutingAssembly().FullName);
            var resourceUri = new Uri(
                String.Format("pack://application:,,,/{0};component/leonidas.jpg", 
                assemblyName.Name));
            using (var stream = Application.GetResourceStream(resourceUri).Stream)
            {
                using (var memoryStream = new MemoryStream())
                {
                    stream.CopyTo(memoryStream);
                    return memoryStream.ToArray();
                }
            }
        }
    }
}

MainWindow.xaml

<Window x:Class="adamprescott.net.DesignTimeDataBinding.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        xmlns:local="clr-namespace:adamprescott.net.DesignTimeDataBinding"
        d:DataContext="{x:Static local:SpartanSampleDataContext.SpartanSampleData}"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <DockPanel VerticalAlignment="Top">
            <Image Source="{Binding Picture}" Height="50" />
            <TextBlock Text="{Binding Profession}" />
        </DockPanel>
    </Grid>
</Window>

Advertisements

4 thoughts on “Design-Time Data Binding in WPF”

    1. There’s always a way to debug! I assume you want a way to set a breakpoint and step through your code in design time, and I don’t have a way for you to do that. You might be able to have your code write to a text file or the output window (Debug.Write) to determine what’s going on. Another option might be to move your code to an easier-to-debug environment and debug it there. For example, you could copy it to a console application in order to step through it line by line with the debugger.

      Those are the best suggestions I can offer off the top of my head.

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s