WPF: Data template for multiple similar data

This entry is part 43 of 54 in the series Learn WPF

When it comes to template, once it is created, we can usually reuse it again and again.

The same goes to WPF data template.

As in the example below, we put the DataTemplate in Resources.  The template is identified by the key personTemplate.

The same personTemplate can be used for the button or the listbox.

<Window x:Class="DataTemplateNSpace.MainWindow"
        Title="MainWindow" Height="350" Width="525">
        <DataTemplate x:Key="personTemplate">
            <Border BorderBrush="Green" BorderThickness="2">
                <StackPanel Margin="4">
                    <TextBlock Foreground="Red" FontSize="20"
                         Text="{Binding Name}"
                         TextAlignment="Center" />
                    <TextBlock FontSize="16" 
                         Text="{Binding Age}"
                         TextAlignment="Right" />
            <RowDefinition Height="Auto"/>
            <RowDefinition />
        <Button Content="{Binding}" Grid.Row="0" ContentTemplate="{StaticResource personTemplate}" />
        <ListBox Grid.Row="1" x:Name="lb" HorizontalContentAlignment="Stretch" ItemTemplate="{StaticResource personTemplate}" />

namespace DataTemplateNSpace
    class Person
        public string Name { get; set; }
        public int Age { get; set; }

using System.Collections.ObjectModel;
using System.Windows;

namespace DataTemplateNSpace
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
        public MainWindow()
            DataContext = new Person { Age = 30, Name = "Carrie Underwood" };

            lb.ItemsSource = new ObservableCollection<Person> {
               new Person { Name = "Katy Perry", Age = 25 },
               new Person { Name = "Taylor Swift", Age = 26 },
               new Person { Name = "Justin Timberlake", Age = 23 }

data template

Series Navigation<< WPF: Data Template
WPF: A simple IValueConverter implementation >>

Leave a comment

Leave a Reply