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.

<Window x:Class="DataTemplateNSpace.MainWindow"
        Title="MainWindow" Height="350" Width="525">
            <RowDefinition Height="Auto"/>
            <RowDefinition />
        <Button Content="{Binding}" Grid.Row="0">
                    <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" />

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

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" };

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.


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