Bookmark and Share Share...    Subscribe to this feed Feed   About Christian Moser  

How to apply a DataTemplate to a ListBox

Introducing DataTemplates

All controls deriving from ItemsControl have a DataTemplate that specifies how an object bound to an item is presented to the user. The default template renders a single line of text per item - as we know a listbox from HTML or WinForms.

But WPF allows us to put whatever we like into a DataTemplate. If we want to display a list of customers we can provide a data template that shows an image for each customer next to its name and age. In my opinion this is one of the most powerful features in WPF.

In the following steps I will show you how to create such an DataTemplate

Bind the data to the ListBox

We bind a list of employees to the listbox. Because the listbox does not know anything about our employee class, it calls the ToString() method. The result is not yet very pleasing.

<Grid x:Name="LayoutRoot">
   <ListBox Margin="10" ItemsSource="{Binding}"/>

Override the ToString() method to improve the display

What we do next is to overriding the ToString() method to provide some useful information instead of just the type name. But a string is not really what we call a cool user experience.

public override string ToString()
    return string.Format("{0} {1} ({2}), {3})", 
                      Firstname, Lastname, Age, Role);

Create a DataTemplate

The ultimate flexibility is to create your own DataTemplate. A data template can consist of multiple controls like images, textblocks, etc. It han have a flexible width and height, background color and shape. There are no limits for your creativity.

An easy way to create a data template is to use Expression Blend. Open the context menu of your list box and choose "Edit Other Templates" -> "Edit Generated Items" -> "Create Empty".

Blend will ask you to specify a name for your DataTemplate because it will define it in the resources of either the Application, the current document of an external resource dictionary. The name you specify is the key for the resource dictionary.

After you press OK, you will be in the editor to design the data template. The item data (in our sample an employee) is set to the DataContext, so you can easily access all properties of the employee by using databinding.

<DataTemplate x:Key="EmployeeDataTemplate">
         <ColumnDefinition Width="60"/>
         <ColumnDefinition Width="*"/>
   <Border Margin="5" BorderBrush="Black" BorderThickness="1">
      <Image Source="{Binding Path=Image}" Stretch="Fill" Width="50" Height="50" />
   <StackPanel Grid.Column="1" Margin="5">
      <StackPanel Orientation="Horizontal" TextBlock.FontWeight="Bold" >
         <TextBlock Text="{Binding Path=Firstname, FallbackValue=FirstName}" />
         <TextBlock Text="{Binding Path=Lastname, FallbackValue=LastName}" Padding="3,0,0,0"/>
      <TextBlock Text="{Binding Path=Age, FallbackValue=Age}" />
      <TextBlock Text="{Binding Path=Role, FallbackValue=Role}" />

Last modified: 2008-10-24 01:06:02
Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments
Commented on 10.June 2009
I had some problem trying to get this one to work.
Commented on 17.June 2009
I suspect people are having problems with this example because there's no data to bind to... Maybe a code snippet that populates a collection when the form loads. This would also reinforce data binding concepts and implementation.
Commented on 9.September 2009
Commented on 26.September 2009
This is funny. I've spent several days searching how to bind data to a listbox. Of all the brilliant authors on the web, not one has the same solution and none make sense.
Commented on 28.September 2009
I saw all of these examples in MSDN before,but the good things is that if it's the first time you want to learn that concept ,it will be more easier to start from here.
Commented on 30.September 2009
\"We bind a list of employees to the listbox\"... WHERE?
Commented on 8.November 2009
I have understood DataTemplate, but how it is used as itemSource of ListBox?
Also how it is binded to Employee objects?
Commented on 10.November 2009
How do you bind the data with the listbox itself? I tried
ItemsSource={Binding Path=Employees}
assuming there is such property as Employees but it does not work (for me at least).
Commented on 19.December 2009
A good example to create a data template for a beginner. But how to set the template to the listbox.
Commented on 5.January 2010
'An easy way to create a data template is to use Expression Blend. Open the context menu of your list box and choose "Edit Other Templates" -> "Edit Generated Items" -> "Create Empty".'

!!!Can't find the menuitem of Edit Other Templates!!!
Commented on 13.January 2010
W. Are you right clicking? The example isn't to teach you how to bind data. He has other examples for that. What is left out of the example is telling your itemscontrol to use your DataTemplate. You can bind by setting the ItemSource of the ItemsControl.
I generally bind in the code... if x:Name="MyControl" then in the code MyControl.ItemsSource where ItemsSource is an Observable collection of the object you want to use.
Commented on 23.January 2010
Very nice example!! Keep it up!
Commented on 4.March 2010
I couldnt get it to work until my class in the Observable collection had public access properties (inside of directly accessing "public string Name" for example). When I did that it worked. Hope this helps.
Commented on 9.June 2010
Its a awsome and helpful tutorial Thanks for helping
Commented on 16.June 2010
would there be any sample for same..? though it looks like gud sample but may be difficult for a beginner..
Commented on 19.August 2010
How would you bind the data template to XML in C#?
Commented on 19.August 2010
How would you bind the data template to XML in C#?
Commented on 24.September 2010
sirs, this is what i wants. can you please send all the code to me please
Commented on 21.October 2010
it's good and so helpfull thx
Commented on 2.January 2011
Sir,would you please paste the complete version of source code here instead of some code snippet. I think that would be more helpful. Thanks!
Commented on 20.January 2011
yep. paste the complete Source Code! Please!
Commented on 6.July 2011
And how to apply a DataTemplate to a ListBox? - like you promised in the Headline. Would be nice if you could paste the complete Source Code :)
Commented on 11.July 2011
Thanks for the stuff and great explanation.
Commented on 12.August 2011
very good
Commented on 2.September 2011
Very Nice Explanation.

E-Mail (optional)