WPF: Data Template

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

WPF data template provides a way for us to present our data.  Data templating helps in presentation of data thereby giving the users a better way to visualize the data.

We will use a button example and using Data Template, we will format the content in the button.

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">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition />
        </Grid.RowDefinitions>
        <Button Content="{Binding}" Grid.Row="0">
            <Button.ContentTemplate>
                <DataTemplate>
                    <Border BorderBrush="Green" BorderThickness="2" Width="200">
                        <StackPanel Margin="4">
                            <TextBlock Foreground="Red" FontSize="20"
                         Text="{Binding Name}"
                         TextAlignment="Center" />
                            <TextBlock FontSize="16" 
                         Text="{Binding Age}"
                         TextAlignment="Right" />
                        </StackPanel>
                    </Border>
                </DataTemplate>
            </Button.ContentTemplate>
        </Button>
    </Grid>
</Window>

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

MainWindow.xaml.cs
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" };
        }
    }
}

In line 10 in MainWindow.xaml, we have

<Button Content="{Binding}" Grid.Row="0">

This will bind the button content to whatever DataContext that is effective.  DataContext is defined in line 13 in MainWindow.xaml.cs.

data_template

Series Navigation<< WPF: Add new data with notification
WPF: Data template for multiple similar data >>