Macca Blog

My life experiences with code and design

Design Time support in Windows 8 C# XAML

Posted on by Mark

If you’re like me, Expression Blend is your best friend while developing any XAML based application.

When the beta’s and release candidates came out for 2012, I found it strange that the ‘Data’ tab in Expression Blend was missing for Windows 8 Metro style applications. I did some digging after the RTM release and found out (from the MS team) that the feature was removed for a reason that they seem to avoid expressing.

You can find my post on the forums here.

However, in the Grid App template in Visual Studio 2012 (which I have recently blogged about) I noticed that they do have full design time support available (see below)…which lead to this post.

Design Time Data in Expression Blend

Design Time Data in Expression Blend

I am going to explore the features in XAML that allow developers to set DataContext’s and Binding using sample data.

Resources

I did my research firstly, as any good developer should do :) and I have found a few quick links that describe this stuff pretty good:

Take a look at these if you have the time, or if you just want info, read ahead

XAML Namespaces

You achieve design time data binding via the blend XSD in your XAML which is (typically) defined under the d: xmlns, for example:

<Page
    x:Class="SampleDataDemo.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:SampleDataDemo"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:data="using:SampleDataDemo.Data"
 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    mc:Ignorable="d" 
>

Its important to note here that there is another property set in the XAML that indicates which namespace to ignore on compilation, the mc:Ignorable=”d” attribute identifies this.

Now that you have the required namespace in your XAML (which is typically added for you by VS2012), you can use the attributes defined in the namespace to get sample data.

Here is an example:

<Grid d:DataContext="{d:DesignData Source=./Data/SampleData.xaml}" />

This sets the DataContext design time property of the Grid control, with the contents of the XAML file located in the Data folder. However, at run time, these attributes are ignored and have no impact on the application.

There are two main attributes used for setting DataContext’s of your Pages/Controls

d:DataContext - Specifies a design-time data context for a control and its children.

d:DesignSource - Specifies a design-time data source for a CollectionViewSource.

You will probably find that 90% of the time, the d:DataContext will suit fine, but sometimes you might use a CollectionViewSource for data binding, in which case the d:DesignSource attribute is your best friend.

Design Time Data Binding

There are 2 approaches for the source of the design time data:

  1. Hard coded C# (code driven) data
  2. XAML file of sample data

Hard coded C# (code driven) data

In order to do this you just need to create a class that is entirely focused on your design time focus. For example:

public class SampleData
{
    public List People { get; set; }
 
    public SampleData()
    {
        People = new List
        {
            new Person {FullName = "Peter", Age = 27},
            new Person {FullName = "Mark", Age = 37},
            new Person {FullName = "Luke", Age = 15}
        };
    }
}

and the Person class is simply:

public class Person
{
    public string FullName { get; set; }
    public int Age { get; set; }
}

as you can see this is a simple set of data, your own sample data or view models will be far more complex than this I’m sure, but you get the idea…

After you have your design time models ready to use, you simply bind this class to your design time data context:

<Grid d:DataContext="{Binding Source={d:DesignInstance Type=data:SampleData, IsDesignTimeCreatable=True}}"
         DataContext="{Binding MyViewModel}"
/>

The above code snippet show binding of the Grid control’s design time DataContext to a “DesignInstace” data source and states that it will create design time created objects, rather than just using the class as type information for binding assistance at design time. As you can also see, you can easily have you ‘real’ DataContext bindings side-by-side with the sample data binding.

The d:DesignInstance attribute is described as such:

Used as part of a d:DataContext or d:DesignSource declaration. Specifies the type that you can use as a data source for binding to controls in the designer. The type does not need to be creatable in XAML.

 XAML file of sample data

Sometimes hard coding data in a C# file simply isn’t good enough and perhaps you want to generate some XAML or author it using XAML.

Good news everyone! You can do this too. Its a very similar approach, you simply use a slightly different binding syntax:

<Grid d:DataContext="{d:DesignData Source=./Data/SampleData.xaml}" />

The above snippet is very simple, and rather self explanatory, however in the interest of completeness I would like to show you an example of the sample XAML file:

<Data:SampleData xmlns:Data="using:SampleDataDemo.Data">
    <Data:SampleData.People>
        <Data:Person Age="33" FullName="Simon" />
        <Data:Person Age="22" FullName="Allan" />
        <Data:Person Age="44" FullName="Chris" />
        <Data:Person Age="11" FullName="Dale" />
        <Data:Person Age="55" FullName="Matt" />
    </Data:SampleData.People>
</Data:SampleData>

Again very simple :)

Conclusion

In summary, XAML has had these features available for a number of years, but I always took for granted how it worked. One thing I did not take for granted was the ability to make use of design time data while developing apps.

The little time it takes to implement some sample data will save you in the long run, trust me.

As always, if you would like some more details, or have comments, please comment, I regularly reply to comments and emails, so feel free to get back to me on anything.

–Mark

This entry was posted in .NET, C#, Design, Developer, Featured, Windows 8, WinRT, XAML. Bookmark the permalink.

7 Responses to Design Time support in Windows 8 C# XAML

  1. I want to learn how to program with Grid App (XAML) in C#. But I haven’t found any ebook or tutorial how to deal with this kind of application. I am new to Metro Style (as anyone) and I want to learn how to iterate with all those group’s on the page of the application. How to change their look and how to use their instances in C# codes? Can you help me find some ebook or just the title of the book which covers my problem?

  2. Hi Antonio, there is a great book called “Building Windows 8 Apps with C# and XAML” that should be able to help you out.

    http://www.amazon.com/gp/product/0321822161/ref=as_li_ss_il?ie=UTF8&camp=1789&creative=390957&creativeASIN=0321822161&linkCode=as2&tag=realworlsofta-20

    Good luck!

  3. I was looking for information on the IsDesignTimeCreatable attribute and found your blog post. Great stuff Mark! Another way I found to work with design time data is to include a d:Source in the <CollectionViewSource tag in your page resources. For example:

    The trick appears to be to make sure to include a sample ObservableCollection of your data type that gets created during the instantiation of the class…

    -mike

  4. Thanks Mike, it was fun to play around with these features, thanks for the tip too!

  5. Bryce

    Great post. I am currently trying to set it at the page level and not having much luck. Basically in the XML namespace declaration where we see our first DataContext being set I added the necessary d:DataContext below it but it seems to have no effect. I’ll try moving it to the Grid instead but do you have any idea why? I got that idea from another blogger and it bugs me that I can’t get it to work.

  6. Debugging these things can be tough, do you know if you class you are using as your sample data is being constructed? If you put an exception in the constructor, does the design time view (within Visual Studio or Blend) show the exception?

  7. Vicente Zambrano

    Hi,
    I have a question.
    How you can update programmatically the item (In your case XML, it can be a Rss feed too), Im trying update my datasource every ten minutes.
    Do you know how.?

Leave a Comment

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>