ItemTemplate is the CollectionView property that receives a DataTemplate for rendering every item in a collection. The template can contain any layout and bind its controls to properties on the individual item, rather than to the whole collection. section 3.4.2 section 3.5
Use ItemTemplate with a collection-based view by following these steps:
- Provide the collection through CollectionView.ItemsSource, commonly by binding it to a list or ObservableCollection. section 3.4.2
- Assign a DataTemplate inside CollectionView.ItemTemplate, then place the desired layout and controls inside it. section 3.4.2
- Bind controls such as Label to properties on each item, such as binding Label.Text to Title. section 3.4.2
- Choose a data template selector when different item properties require different templates at runtime. section 4.3
Rendering to-do items
A to-do list can replace a newline-separated Label with a CollectionView. Its ItemTemplate can define a Grid containing a CheckBox and a wrapped, bold Label bound to each TodoItem’s Title. Binding the view to an ObservableCollection lets added or removed items update through the XAML engine. section 3.4.2
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 a complete XAML ItemTemplate that lays out each to-do item with Grid, CheckBox, and Label elements. section 3.4.2
