ObservableCollection<T> is a .NET collection that works like List<T> while notifying the XAML binding system when items are added or removed. Bound controls can refresh automatically without separate update code. section 3.4.2
Use ObservableCollection when a .NET MAUI page displays a changing set of objects:
- Declare a typed property, such as ObservableCollection<TodoItem> Todos { get; set; } = new();. section 3.4.2
- Import System.Collections.ObjectModel. section 3.4.2
- Assign the collection to a control's ItemsSource, then call Todos.Add(todo) when new data arrives. section 3.4.2
- Define an item template so bindings such as {Binding Title} control each rendered item. section 3.4.2
To-do list
A .NET MAUI to-do page replaces a newline-separated Label with a CollectionView. The view binds to an ObservableCollection<TodoItem>, allowing added or removed to-dos to appear automatically and enabling templates for titles, due dates, and item-specific formatting. section 3.4.2
Movie browser
A movie page stores genres and movies in separate ObservableCollection properties. The collections supply data to XAML bindings and layouts, including a wrapped movie display populated from API results. section 6.2.1
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>
Shows the CollectionView, item template, and property binding used to render each to-do item. section 3.4.2
