User Tools

Site Tools


This is an old revision of the document!

DataTemplate in XAML

DataTemplate is usually used with list controls such as ItemsControl, GridView, or ListView.

Example: Define a DataTemplate inline by setting the ItemTemplate property. The ItemTemplate property is of type DataTemplate:

            <Rectangle Width="100" Height="50" Margin="10">
                    <SolidColorBrush Color="{Binding}" />

Example: Define a DataTemplate inline and bind the ItemsControl to an ObservableCollection:

<Page x:Class="TestApp.MainPage"
        <ItemsControl ItemsSource="{x:Bind People}">
                <DataTemplate x:DataType="local:Person">
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{x:Bind FirstName}" Margin="0,0,4,0"/>
                        <TextBlock Text="{x:Bind LastName}"/>
using System.Collections.ObjectModel;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace TestApp
    class Person
        public string FirstName { get; set; }
        public string LastName { get; set; }
    public sealed partial class MainPage : Page
        private ObservableCollection<Person> People;
        public MainPage()
            People = new ObservableCollection<Person>();
            Loaded += MainPage_Loaded;
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
            People.Add(new Person { FirstName = "John", LastName = "Makak" });
            People.Add(new Person { FirstName = "Steve", LastName = "Gibbon" });
            People.Add(new Person { FirstName = "Mike", LastName = "Chimp" });
notes/uwp/datatemplate.1482328345.txt.gz · Last modified: 2020/08/26 (external edit)