Click here to Skip to main content
15,867,141 members
Articles / Desktop Programming / WPF

WPF UserControl == DataTemplate!!!

Rate me:
Please Sign up or sign in to vote.
4.88/5 (41 votes)
8 Aug 2008CPOL6 min read 275.7K   6.9K   103   45
Demos how to use a WPF UserControl as a DataTemplate.

UserControlAsDataTemplate-M.png

Introduction

If you're either learning WPF or are using WPF extensively, you will without doubt have the need for DataTemplates. DataTemplates allow the developer to define how and what is bound and rendered in the User Interface from the underlying application objects. They are, to put it plainly, ubiquitous when it comes to displaying data in a WPF User Interface.

When you have a collection of objects that are to be shown in the User Interface in a logical and common way, a DataTemplate is the method of choice to define the look and feel of those elements once they are rendered in the UI. They fuel consistency, and are intrinsically reusable. The demo source code included with this article is very simple, but if you combine these ideas with other possibilities, such as value converters, you will soon find that you have a very powerful set of UI tools at your disposal.

There are many, many sources of information on The Code Project and the Internet, in general that, can explain the general DataTemplate principals better than I. The best place to start in order to learn some of the fundamentals of defining and using DataTemplates will be the MSDN documentation that can be found here: MSDN - DataTemplates.

Inline Templates

DataTemplates are often defined 'inline', meaning that they are constructed within an items control XAML structure in the main 'consuming' XAML file, such as:

XML
<ListBox Width="400" Margin="10"
  ItemsSource="{Binding Source={StaticResource myTodoList}}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Path=TaskName}" />
<TextBlock Text="{Binding Path=Description}"/>
<TextBlock Text="{Binding Path=Priority}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

Or, they are often contained within the Resources section of a Window, Page, or Control, such as:

XML
<Window.Resources>
<DataTemplate x:Key="myTaskTemplate">
<StackPanel>
<TextBlock Text="{Binding Path=TaskName}" />
<TextBlock Text="{Binding Path=Description}"/>
<TextBlock Text="{Binding Path=Priority}"/>
</StackPanel>
</DataTemplate>
</Window.Resources>

Alternatives

One other method is possible which doesn't actually seem to get much press. To be honest, I personally feel the method I'm covering here is most 'agreeable' in relation to the whole Designer paradigm that WPF has thrown at us. You can use UserControls as DataTemplates! This is such a neat solution that I sat down to put together this little demo of how this is done so that others can get an easy look at the idea and start using this method.

One point that is continually made about WPF is its ability to allow 'loose coupling' of application logic and User Interface implementations. By making UserControls that are designed to be used as DataTemplates, you can really take this further and have a clean separation between the main Window or Page XAML and the DataTemplates. Anyway, let's look at some code!!

Using the Code

For this demo, I started off by creating a normal Visual Studio 2008 solution. Then, I defined a DataItem class to hold some data to be shown in the UI:

C#
/// <summary>
/// A simple class holding a few items of data in various formats
/// </summary>
public sealed class DataItem
{
    public string Name { get; set; }
    public int Age { get; set; }
    public double Progress { get; set; }

    /// <summary>
    /// A parameterised constructor
    /// </summary>
    /// <param name="name"></param>
    /// <param name="age"></param>
    /// <param name="progress"></param>
    public DataItem(string name, int age, double progress)
    {
        Name = name;
        Age = age;
        Progress = progress;
    }
}

Now that we have a simple object defined that we want to display in the UI, we need to setup the consumption of this object and populate it with some data. To do this, I simply defined an ObservableCollection in the window and created a method that stuffed in some DataItem objects into the collection:

C#
ObservableCollection<DataItem> items = new ObservableCollection<DataItem>();

Within the main window code-behind file, I added this method:

C#
void PopulateDataItems()
{
    items.Add(new DataItem("Jammer", 32, 10.0));
    items.Add(new DataItem("John", 44, 20.0));
    items.Add(new DataItem("Jane", 25, 30.0));
    items.Add(new DataItem("Robert", 30, 40.0));
    items.Add(new DataItem("Jezzer", 50, 50.0));
    items.Add(new DataItem("James", 40, 60.0));
    items.Add(new DataItem("Rebecca", 25, 70.0));
    items.Add(new DataItem("Mark", 35, 80.0));
    items.Add(new DataItem("Leah", 20, 90.0));
    items.Add(new DataItem("WallE", 700, 100.0));
}

Done! We now have a window code-behind that defines a collection and adds the correct objects to that collection ready for display in the UI. The next thing to look at is the XAML that uses all of this WPF goodness.

First of all, I created a UserControl (ProgressReporter.xaml) to display the Progress property of the DataItem class:

XML
<UserControl 
x:Class="UserControlAsDataTemplateDemo.UserControls.ProgressReporter"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="ProgressControl"
Height="Auto" Width="Auto">
<Grid>
<ProgressBar x:Name="UIReporter" 
Value="{Binding PercentToShow, ElementName=ProgressControl}" 
HorizontalAlignment="Stretch" 
VerticalAlignment="Stretch" 
Style="{DynamicResource ProgressReporterStyle}" />
</Grid>
</UserControl>

UserControl-ProgressReporter.png

The code-behind for this control also defines a custom DependencyProperty that the ProgressBar uses to obtain its value from:

C#
/// <summary>
/// The dependency property of the ProgressReporter
/// UserControl to display in the GUI
/// </summary>
public static DependencyProperty PercentProperty =
          DependencyProperty.Register("PercentToShow",
          typeof(double), typeof(ProgressReporter));

/// <summary>
/// The PercentToShow value
/// </summary>
public double PercentToShow
{
    get { return (double)GetValue(PercentProperty); }
    set { SetValue(PercentProperty, value); }
}

Next up is the UserControl that is going to be used as the DataTemplate.

XML
<UserControl
x:Class="UserControlAsDataTemplateDemo.UserControls.ItemTemplateControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:UserControls="clr-namespace:UserControlAsDataTemplateDemo.UserControls"
Height="Auto" Width="Auto">
<Border BorderThickness="2,2,2,2" 
CornerRadius="5,5,5,5" 
Background="#FF626262" 
BorderBrush="#FFFFAC00" 
Grid.ColumnSpan="2">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBox HorizontalAlignment="Stretch" 
VerticalAlignment="Stretch" 
Text="{Binding Path=Name}" 
TextWrapping="Wrap" 
Margin="4,4,4,4" 
Grid.ColumnSpan="1"/>
<TextBox HorizontalAlignment="Stretch" 
VerticalAlignment="Stretch" 
Text="{Binding Path=Age}" 
TextWrapping="Wrap" 
Grid.Column="1" 
Margin="4,4,4,4" 
Grid.ColumnSpan="1"/>
<UserControls:ProgressReporter 
HorizontalAlignment="Stretch" 
VerticalAlignment="Stretch" 
PercentToShow="{Binding Path=Progress}" 
Grid.Column="2" Margin="4,4,4,4" />
</Grid>
</Border>
</UserControl>

The main points to note here are the Binding settings. You can see that the text boxes are bound to the Name and Age properties of the DataItem class, and that the custom DependencyProperty called PercentToShow is used to bind the double property Progress from the DataItem class to the ProgressReporter control.

The image below shows the DataTemplate UserControl in Expression Blend:

ItemControltemplate.png

Now that we have the 'DataTemplate' UserControl defined, the only thing left to do is write the XAML in the MainWindow that will use this control as a DataTemplate. The XAML for this looks like:

XML
<ListBox x:Name="peopleListBox" 
HorizontalAlignment="Stretch" 
VerticalAlignment="Stretch"
ItemContainerStyle="{StaticResource ListBoxItemStretch}"
Foreground="Transparent" 
BorderBrush="Transparent" 
Background="Transparent" 
Grid.ColumnSpan="2">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<UserControls:ItemTemplateControl Margin="4" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

So, when you run the application and hit the [Load Data] button, it uses the PopulateDataItems() method and then binds the ObservableCollection 'items' to the listbox and renders each DataItem using our UserControl:

C#
private void btnLoadData_Click(object sender, RoutedEventArgs e)
{
    // Reset the Items Collection
    items.Clear();

    // Populate the Items Collection 
    PopulateDataItems();

    // Bind the items Collection to the List Box
    peopleListBox.ItemsSource = items;
}

Adding in Dynamic Behaviour using Code-Behind

Once you have defined and used your custom UserControl as a DataTemplate, you will more than likely wish to make them a bit smarter and more WPF'y. There are a variety of ways to do this through the use of mechanisms like Triggers, DataTriggers, and Value Converters. One thing that we can now do in addition to this is simply use the C# code-behind file to build in some dynamic behaviour into the DataTemplate. You will find the complete source for this dynamic example in the included source file at the top of this article.

In order to fully show this dynamic behaviour, I have made a few changes to the data creation methods used in the original sample; I have randomised the progress value being used in the DataItems by doing this:

C#
private void PopulateDataItems()
{
    items.Add(new DataItem("Jammer", 32, MakeRandomDouble()));
    items.Add(new DataItem("John", 44, MakeRandomDouble()));
    items.Add(new DataItem("Jane", 25, MakeRandomDouble()));
    items.Add(new DataItem("Robert", 30, MakeRandomDouble()));
    items.Add(new DataItem("Jezzer", 50, MakeRandomDouble()));
    items.Add(new DataItem("James", 40, MakeRandomDouble()));
    items.Add(new DataItem("Rebecca", 25, MakeRandomDouble()));
    items.Add(new DataItem("Mark", 35, MakeRandomDouble()));
    items.Add(new DataItem("Leah", 20, MakeRandomDouble()));
    items.Add(new DataItem("WallE", 700, MakeRandomDouble()));
}

private double MakeRandomDouble()
{
    int randomnumber = _random.Next(1, 100);
    return (double)randomnumber;
}

To drive the dynamic behaviour that will react to this random data, I have added in code into the Loaded event of the ItemTemplateControl:

XML
Loaded="UserControl_Loaded"

The Loaded event is fired after the data binding has taken place and after Layout has been run on the element. This means we have access to the actual data values in order to react accordingly to these values and make the changes we want too just before display in the UI. The code in this event handler is as follows:

C#
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
    if (Convert.ToInt32(this.AgeTextBox.Text) > 40)
    {
        SolidColorBrush brush = new SolidColorBrush();
        brush.Color = Colors.DarkGray;
        MainBorder.Background = brush;
    }

    if (this.ProgressReporter.PercentToShow > 80.0)
    {
        SolidColorBrush brush = new SolidColorBrush();
        brush.Color = Colors.Lavender;
        MainBorder.Background = brush;
    }

    // An extension method to create and start an animation
    Animations.Fade(this, 0.0, (ProgressReporter.PercentToShow / 100), 1000);
}

This is all fairly straightforward stuff. One major point to make here is that we have given some controls names using x:Name=""; this allows us to easily access these controls in the associated class. We are reacting to the numeric value of the AgeTextBox.Text and the PercentToShow value of the ProgressReporter. In each case, we are then creating a new SolidColorBrush object and applying that to the background color of the MainBorder object in order to highlight the control in the UI based on the bound values. You will also note that we are using an extension method that wraps a DoubleAnimation called Fade();.

In order to add in some more WPFness, I have created a new static class called Animations, that looks like this:

C#
public static class Animations
{
    static Animations()
    {
    }

    public static void Fade(this UIElement control, 
           double sourceOpacity, double targetOpactity, int milliseconds)
    {
        control.BeginAnimation(UIElement.OpacityProperty,  
          new DoubleAnimation(sourceOpacity,targetOpactity, 
          new Duration(TimeSpan.FromMilliseconds(milliseconds))));
    }
}

And there we go, we have now added in some pretty cool dynamic behaviour using just the code-behind of a UserControl. This could be massively expanded on, but would over complicate the example.

UserControlDynamicScreenShot.png

It's a Wrap(per)

One of the main benefits of this approach from my point of view is that when designing DataTemplates, it's easy to feel disconnected from the actual design process. By using a UserControl as a DataTemplate, you are afforded the full design flow of using Expression Blend to write the XAML for the DataTemplate. Personally, I find that to be a compelling reason to use this approach for most DataTemplate designs, unless you are using a very basic design combined with predefined styles for any elements within that DataTemplate you may need.

Either way, I hope this little demo has been useful and that you find some uses for this approach. This is merely skimming the potential!

History

  • 23 July 2008 - Initial version.
  • 08 August 2008 - Added in Dynamic Code examples.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Chief Technology Officer JamSoft Solution Ltd
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionGODLY Tutorial Pin
Member 124359427-Apr-16 5:30
Member 124359427-Apr-16 5:30 
AnswerRe: GODLY Tutorial Pin
Jammer22-May-16 3:12
Jammer22-May-16 3:12 
QuestionMislabeled post Pin
Phillip Givens25-Sep-12 18:21
Phillip Givens25-Sep-12 18:21 
AnswerRe: Mislabeled post Pin
Jammer26-Sep-12 23:15
Jammer26-Sep-12 23:15 
GeneralMore than once this helped me out! Pin
Fonzerelli18-Nov-11 22:50
Fonzerelli18-Nov-11 22:50 
GeneralRe: More than once this helped me out! Pin
Jammer26-Sep-12 23:15
Jammer26-Sep-12 23:15 
GeneralMy vote of 5 Pin
Xanblax31-Jan-11 1:12
Xanblax31-Jan-11 1:12 
VERY useful. To get a ListView of UserControls is a must in many UI cases. And it is not as obvious as it should be within the VS. This article explains it neat and clean.
GeneralRe: My vote of 5 Pin
Jammer26-Sep-12 23:16
Jammer26-Sep-12 23:16 
Generalalternative text Pin
mbthe2nd24-Sep-09 6:34
mbthe2nd24-Sep-09 6:34 
GeneralRe: alternative text Pin
Jammer25-Sep-09 8:34
Jammer25-Sep-09 8:34 
GeneralNice tip! Pin
Sevenate12-Jun-09 4:12
Sevenate12-Jun-09 4:12 
GeneralRe: Nice tip! Pin
Jammer12-Jun-09 8:48
Jammer12-Jun-09 8:48 
QuestionDependencyProperty of UserControl child in databound UserControl not getting updates Pin
Kim Svedmark8-Jun-09 23:21
Kim Svedmark8-Jun-09 23:21 
AnswerRe: DependencyProperty of UserControl child in databound UserControl not getting updates Pin
Jammer12-Jun-09 8:47
Jammer12-Jun-09 8:47 
GeneralWow Super 5/5 Pin
prasad0217-Feb-09 16:11
prasad0217-Feb-09 16:11 
GeneralUsing ElementName binding inside a DataTemplate Pin
chaiguy13372-Dec-08 11:16
chaiguy13372-Dec-08 11:16 
GeneralRe: Using ElementName binding inside a DataTemplate Pin
Jammer2-Dec-08 12:28
Jammer2-Dec-08 12:28 
GeneralRe: Using ElementName binding inside a DataTemplate Pin
chaiguy13372-Dec-08 12:46
chaiguy13372-Dec-08 12:46 
QuestionAdvantage of XAML long form for ListBox.ItemTemplate? Pin
RNEELY14-Aug-08 3:52
RNEELY14-Aug-08 3:52 
AnswerRe: Advantage of XAML long form for ListBox.ItemTemplate? Pin
Jammer14-Aug-08 6:38
Jammer14-Aug-08 6:38 
QuestionSomething you might be able to help me with Pin
joker79711-Aug-08 11:22
joker79711-Aug-08 11:22 
AnswerRe: Something you might be able to help me with Pin
Jammer11-Aug-08 12:12
Jammer11-Aug-08 12:12 
GeneralRe: Something you might be able to help me with Pin
joker79712-Aug-08 7:09
joker79712-Aug-08 7:09 
GeneralRe: Something you might be able to help me with Pin
Jammer12-Aug-08 7:25
Jammer12-Aug-08 7:25 
GeneralCodeBehind DataTemplate Pin
RNEELY31-Jul-08 0:29
RNEELY31-Jul-08 0:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.