A DataTemplate defines the user-interface structure used to display one data object. It is most often assigned to a collection control’s ItemTemplate, letting the control render every item in an ItemsSource with the same layout instead of reducing a list to plain text. section 3.4.2 section 4.3
Inside an item template, the binding context is the individual item, not the whole collection. Bind child views directly to that item’s properties: for example, a Label can bind Text to Title. This makes each repeated layout show the corresponding object’s values. section 3.4.2
Use a DataTemplate to turn collection data into a useful interface:
- With CollectionView, bind ItemsSource to a collection and assign the DataTemplate to ItemTemplate. section 3.5
- Use layouts, controls, and bindings inside the template to show several properties, such as a to-do title, due date, and completion state. section 3.4.2
- Use BindableLayout with layouts such as FlexLayout when items should wrap or follow a custom arrangement. section 6.2.1 section 6.5
- Use a data template selector when different item properties must choose different templates at runtime. section 4.3
Template a to-do list item
A CollectionView can display an ObservableCollection of to-do items. Its ItemTemplate contains a DataTemplate with a Grid, CheckBox, and Label bound to Title. The Grid supplies the repeated item layout, while each generated row receives one to-do item as its binding context. section 3.4.2
Build richer list rows
A message list can use a Grid-based DataTemplate with an avatar, sender, subject, body preview, and sent time. A product-search list can instead use a VerticalStackLayout that binds labels to Name and ManufacturerName, while CollectionView handles selection separately. section 6.4.8 section 9.5.3
Listing 3.14 To-dos CollectionView
<CollectionView Grid.Row="4"
x:Name="TodosCollection"> #1
<CollectionView.ItemTemplate> #2
<DataTemplate> #3
<Grid WidthRequest="350" #4
Padding="10"
Margin="0,20"
ColumnDefinitions="2*, 5*" #5
RowDefinitions="Auto, 50" #6
x:Name="TodoItem">
<CheckBox VerticalOptions="Center" #7
HorizontalOptions="Center"
Grid.Column="0"
Grid.Row="0" />
<Label Text="{Binding Title}" #8
FontAttributes="Bold"
LineBreakMode="WordWrap"
HorizontalOptions="StartAndExpand"
FontSize="Large"
Grid.Row="0"
Grid.Column="1"/>
<Label Text="{Binding Due, StringFormat=
'{0:dd MMM yyyy}'}" #9
Grid.Column="1"
Grid.Row="1"/>
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
Inspect the inline CollectionView template: ItemTemplate contains a DataTemplate whose Grid and child controls define one rendered to-do item. section 3.4.2
