WPF: Data template for multiple similar data

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.

MainWindow.xaml
<Window x:Class="DataTemplateNSpace.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <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" />
                </StackPanel>
            </Border>
        </DataTemplate>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition />
        </Grid.RowDefinitions>
        <Button Content="{Binding}" Grid.Row="0" ContentTemplate="{StaticResource personTemplate}" />
        <ListBox Grid.Row="1" x:Name="lb" HorizontalContentAlignment="Stretch" ItemTemplate="{StaticResource personTemplate}" />
    </Grid>
</Window>

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

MainWindow.xaml.cs
using System.Collections.ObjectModel;
using System.Windows;

namespace DataTemplateNSpace
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            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 >>