We have all used WPF DataTemplates, but I bet most of you never gave thought to the meaning of the x:Key attribute. We all know the meaning of the DataType attribute, which determines to what type of data the template will apply to. But what about the x:Key why is it there? Lets tale a look at the following code:

        <DataTemplate DataType="{x:Type data:s}">
            <Button Width="50" Height="50">
                <TextBlock Text="{Binding text}"></TextBlock>
        <ItemsControl ItemsSource="{Binding}">

If we set the DataContext of the ItemsControl to be a list of ‘s’ type classes the Template will apply to all of them anywhere in the Window. Now lets add a x: key to the DataTemplate like this:

<DataTemplate DataType="{x:Type data:s}" x:Key="ButtonTemplate">
            <Button Width="50" Height="50" Background=">
                <TextBlock Text="{Binding text}"></TextBlock>

If you run this you will notice that the template will no longer apply to any ‘s’ type class. If we want it to apply we will have to make the ItemsControl look like this:

<ItemsControl ItemsSource="{Binding}"
              ItemTemplate="{StaticResource ButtonTempate}"/>

So why do we need the x:key for? It only complicates things. Well the answer is that we need it more than we need the DataType attribute.

Have you ever tried to create a WPF DataTemplate for an interface? If not, then don’t even try, it is not supported, read more about WPF DataTemplate for Interfaces here. Using the x:key is kind of a way around it. If you want your control to be compatible with several types of data, all you need to do is define the DataTemplate in the following way:

<DataTemplate x:Key="ButtonTempate">
            <Button Width="50" Height="50">
                <TextBlock Text="{Binding text}"></TextBlock>

Can you see the difference I actually dropped the DataType attribute. This DataTemplate does not care what is the data type it is using, as long as the data object has a ‘text’ property for the binding everything will work fine.

All you need to do is define an interface that requires implementing the text property and any class that implements that interface will make this Template work.



Tags :

3 Responses to “Why Should You Use The x:key Attribute In WPF DataTemplates”

  1. snapper riding mowers

    Said on March 27, 2014 :

    Mowing high and watering deeply and infrequently in and of itself will help encourage deeper rooted grass and less weeds.
    There are currently dozens of free-to-low cost avenues of publicity
    you can take advantage of. If you own fescue, cut it down to two or
    two and a half inches.

2 Trackback(s)

  1. Apr 9, 2009: DebuggerDisplay and DebuggerBrowsable – Two Debugger Attributes you should know | Dev102.com
  2. Sep 6, 2009: WPF: 90+ Miejsc które warto zna? « Dawid Po?li?ski

Post a Comment