Creating a DataTemplate

Specifying the appearance of data

PDF for offline use:
Sample Code:
Related Articles:
Related APIs:

Let us know how you feel about this.


0/250
Thanks for the feedback!

last updated: 2016-03

Data templates can be created inline, or in a ResourceDictionary. An inline template, which is one that's placed as a direct child of an appropriate control property, should be used if there's no need to reuse the data template elsewhere. Alternatively, a DataTemplate can be defined as a control-level, page-level, or application-level resource. This article demonstrates both techniques.

Creating an Inline DataTemplate

A common usage scenario for a DataTemplate is displaying data from a collection of objects in a ListView. The appearance of the data for each cell in a ListView can be managed by setting the ListView.ItemTemplate property to an inline DataTemplate. The elements specified in the DataTemplate define the appearance of each cell, as shown in the following XAML code example:

<ListView x:Name="listView">
  <ListView.ItemTemplate>
    <DataTemplate>
      <ViewCell>
        <Grid>
          ...
          <Label Text="{Binding Name}" FontAttributes="Bold" />
          <Label Grid.Column="1" Text="{Binding Age}" />
          <Label Grid.Column="2" Text="{Binding Location}" ... />
        </Grid>
      </ViewCell>
    </DataTemplate>
  </ListView.ItemTemplate>
</ListView>

In a ListView, the child of a DataTemplate, must be of, or derive from, type ViewCell. Layout inside the ViewCell is managed here by a Grid. The Grid contains three Label instances that bind their Text properties to the appropriate properties of each Person object in the collection.

Specifying a DataTemplate in C# is more verbose than it's XAML equivalent, as shown in the following code example:

public class WithDataTemplatePageCS : ContentPage
{
  public WithDataTemplatePageCS ()
  {
    ...
    var people = new List<Person> {
      new Person ("Steve", 21, "USA"),
      ...
    };

    var personDataTemplate = new DataTemplate (() => {
      var grid = new Grid ();
      ...
      var nameLabel = new Label { FontAttributes = FontAttributes.Bold };
      var ageLabel = new Label ();
      var locationLabel = new Label { HorizontalTextAlignment = TextAlignment.End };

      nameLabel.SetBinding (Label.TextProperty, "Name");
      ageLabel.SetBinding (Label.TextProperty, "Age");
      locationLabel.SetBinding (Label.TextProperty, "Location");

      grid.Children.Add (nameLabel);
      grid.Children.Add (ageLabel, 1, 0);
      grid.Children.Add (locationLabel, 2, 0);

      return new ViewCell { View = grid };
    });

    var listView = new ListView { ItemsSource = people, ItemTemplate = personDataTemplate };
    Content = new StackLayout {
      Padding = new Thickness (0, 20, 0, 0),
      Children = {
        ...
        listView
      }
    };
  }
}

Alternatively, the DataTemplate can be created from a custom cell class by using the typeof operator. For more information, including customizing the appearance of cells, see Cell Appearance.

The following screenshots show the result of the appearance of each cell in the ListView being defined by a DataTemplate:

Creating a DataTemplate as a Resource

In addition to creating an inline DataTemplate, they can also be created as reusable objects in a ResourceDictionary. This is achieved by giving each declaration a unique x:Key attribute, which provides it with a descriptive key in the ResourceDictionary, as shown in the following XAML code example:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="DataTemplates.WithDataTemplatePage" Title="With a Data Template" Icon="xaml.png">
    <ContentPage.Resources>
        <ResourceDictionary>
            <DataTemplate x:Key="personTemplate">
                <ViewCell>
                    <Grid>
                        ...
                    </Grid>
                </ViewCell>
            </DataTemplate>
        </ResourceDictionary>
    </ContentPage.Resources>
    <StackLayout Padding="0,20,0,0">
        ...
        <ListView x:Name="listView" ItemTemplate="{StaticResource personTemplate}" />
    </StackLayout>
</ContentPage>

The DataTemplate is then assigned to the ListView.ItemTemplate property by using the StaticResource markup extension. Note that while the DataTemplate is defined in the page's ResourceDictionary, it could also be defined at the control level or application level.

The following code example shows the equivalent page in C#:

public class WithDataTemplatePageCS : ContentPage
{
  public WithDataTemplatePageCS ()
  {
    ...
    var personDataTemplate = new DataTemplate (() => {
      var grid = new Grid ();
      ...
      return new ViewCell { View = grid };
    });

    Resources = new ResourceDictionary ();
    Resources.Add ("personTemplate", personDataTemplate);

    var listView = new ListView { ItemsSource = people, ItemTemplate = (DataTemplate)Resources ["personTemplate"] };
    Content = new StackLayout {
      Padding = new Thickness (0, 20, 0, 0),
      Children = {
        ...
        listView
      }
    };
  }
}

The DataTemplate is added to the ResourceDictionary using the Add method, which specifies a Key string that is used to reference the DataTemplate when retrieving it.

Summary

This article has demonstrated how to create data templates, both inline and in a ResourceDictionary. An inline template should be used if there's no need to reuse the data template elsewhere. Alternatively, a DataTemplate can be defined as a control-level, page-level, or application-level resource, with the resource being referenced as a value of the appropriate property.

Xamarin Workbook

If it's not already installed, install the Xamarin Workbooks app first. The workbook file should download automatically, but if it doesn't, just click to start the workbook download manually.