Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 42 ยท Controls and Binding

CollectionView and Lists

Show lists in .NET MAUI with CollectionView: ItemsSource, DataTemplate, ObservableCollection, selection, grouping, EmptyView, RefreshView and layouts, with runnable collection stand-ins.

Nearly every app shows a list: messages, products, tasks, search results. In .NET MAUI the control for this is CollectionView. It displays a collection of items using a template you design, virtualizes the rows (only the rows near the screen are created, so a list of 10,000 items stays fast) and supports selection, grouping, headers and different layouts.

CollectionView needs the real MAUI, so the XAML is read-only. The C# stand-ins use the real ObservableCollection<T> and INotifyCollectionChanged from .NET to show exactly what the list control listens to.

A first CollectionView

XML
<CollectionView ItemsSource="{Binding Products}">
    <CollectionView.ItemTemplate>
        <DataTemplate x:DataType="models:Product">
            <Grid Padding="12" ColumnDefinitions="*,Auto">
                <Label Text="{Binding Name}" FontSize="18" />
                <Label Grid.Column="1" Text="{Binding Price, StringFormat='{0:C}'}" />
            </Grid>
        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>
  • ItemsSource is any IEnumerable. For a list that never changes, List<T> is fine.
  • ItemTemplate is a DataTemplate: the XAML inside is instantiated once per item, and each copy gets that item as its BindingContext. So {Binding Name} means item.Name.
  • Add x:DataType to the DataTemplate so the bindings are compiled (see Data Binding Basics).

Do not put a CollectionView inside a VerticalStackLayout that is inside a ScrollView: the list would measure all its items and lose virtualization. Give the list a bounded space, for example by putting it in a Grid row with a * height, as the layout lessons explain.

ObservableCollection: telling the list about changes

If you change a plain List<T> after the page appeared, the list does not notice. ObservableCollection<T> raises CollectionChanged when items are added, removed, moved or replaced, and CollectionView listens to it:

C#
public class ShopViewModel
{
    public ObservableCollection<Product> Products { get; } = new()
    {
        new("Tea", 3.5m),
        new("Coffee", 4.2m),
    };

    public void AddProduct() => Products.Add(new("Cocoa", 3.9m));   // the row appears
}

Two rules matter. First, ObservableCollection notifies for the collection, not for item properties; if an item's Price changes and the row should update, the Product class needs INotifyPropertyChanged. Second, change the collection on the UI thread; if a background task fills it, marshal the call with MainThread.BeginInvokeOnMainThread.

Replacing the whole collection, Products = newList, works only when the property raises PropertyChanged and the binding reads the new object. Adding hundreds of items one by one is slower than creating a new collection and assigning it once.

C# Stand-in: what the list sees

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Layouts

ItemsLayout decides how rows are arranged:

XML
<!-- default: a vertical list -->
<CollectionView ItemsLayout="VerticalList" />

<!-- horizontal carousel of cards -->
<CollectionView ItemsLayout="HorizontalList" HeightRequest="140" />

<!-- grid of 2 columns -->
<CollectionView>
    <CollectionView.ItemsLayout>
        <GridItemsLayout Orientation="Vertical" Span="2"
                         VerticalItemSpacing="8" HorizontalItemSpacing="8" />
    </CollectionView.ItemsLayout>
</CollectionView>

LinearItemsLayout adds ItemSpacing, and SnapPointsType="MandatorySingle" with SnapPointsAlignment="Center" snaps a horizontal list like a pager. For a one-item-at-a-time pager with indicators, there is also the separate CarouselView.

Selection

By default nothing is selectable. Turn selection on with SelectionMode:

XML
<CollectionView ItemsSource="{Binding Products}"
                SelectionMode="Single"
                SelectedItem="{Binding SelectedProduct, Mode=TwoWay}"
                SelectionChangedCommand="{Binding OpenProductCommand}"
                SelectionChangedCommandParameter="{Binding SelectedItem, Source={RelativeSource Self}}" />
  • Single gives SelectedItem; Multiple gives SelectedItems (an IList<object>), but binding SelectedItems is one-way: you cannot assign it from the view model in a simple way.
  • The SelectionChanged event delivers PreviousSelection and CurrentSelection.
  • After you navigate to a detail page, set SelectedItem = null (or clear it in OnAppearing) so the same row can be tapped again.

For a tap on a row that is not a "selected" state, add a TapGestureRecognizer to the template instead, with a command parameter bound to the item.

Empty lists, headers and footers

XML
<CollectionView ItemsSource="{Binding Products}">
    <CollectionView.Header>
        <Label Text="Products" FontSize="24" Margin="12" />
    </CollectionView.Header>

    <CollectionView.EmptyView>
        <VerticalStackLayout Padding="40" HorizontalOptions="Center">
            <Label Text="Nothing here yet" FontSize="18" />
            <Label Text="Tap + to add your first product." />
        </VerticalStackLayout>
    </CollectionView.EmptyView>

    <CollectionView.Footer>
        <Label Text="{Binding Products.Count, StringFormat='{0} items'}" Margin="12" />
    </CollectionView.Footer>
</CollectionView>

EmptyView is shown whenever ItemsSource is null or has no items, which makes it perfect for "no results" messages. A different template per item type is possible with ItemTemplateSelector, a class that returns a DataTemplate for each item.

Grouping

Set IsGrouped="True" and bind to a list of groups. A group is a list that has extra properties, usually a name:

C#
public class ProductGroup : List<Product>
{
    public string Name { get; }
    public ProductGroup(string name, IEnumerable<Product> items) : base(items) => Name = name;
}
XML
<CollectionView ItemsSource="{Binding Groups}" IsGrouped="True">
    <CollectionView.GroupHeaderTemplate>
        <DataTemplate x:DataType="vm:ProductGroup">
            <Label Text="{Binding Name}" FontAttributes="Bold" BackgroundColor="LightGray" Padding="8" />
        </DataTemplate>
    </CollectionView.GroupHeaderTemplate>
    <CollectionView.ItemTemplate>
        <DataTemplate x:DataType="models:Product">
            <Label Text="{Binding Name}" Padding="12,4" />
        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>

LINQ makes building groups easy. The stand-in below groups products by category and prints the result as the grouped list would show it.

C# Stand-in: grouping and filtering a list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Pull to refresh, loading more and performance

Wrap the list in a RefreshView for pull-to-refresh:

XML
<RefreshView IsRefreshing="{Binding IsRefreshing}" Command="{Binding RefreshCommand}">
    <CollectionView ItemsSource="{Binding Products}" />
</RefreshView>

For endless lists, set RemainingItemsThreshold="5" and handle RemainingItemsThresholdReachedCommand to load the next page.

For smooth scrolling keep templates light: avoid deep nesting (prefer a Grid over many stacked layouts), keep images a sensible size, give rows a fixed HeightRequest when possible and use compiled bindings. Test on a real mid-range phone, not only on a fast emulator.

A CollectionView at a glance

ItemsSource Any IEnumerable, ideally ObservableCollection
ItemTemplate One row design, one BindingContext per item
Virtualization Only visible rows are created
SelectionMode None, Single or Multiple

Bound space and compiled bindings keep long lists smooth.

1 / 2

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why use ObservableCollection<T> instead of List<T> for a bound list?

    CollectionView subscribes to CollectionChanged. A List<T> gives no notifications after the list is shown.
  2. 2. What is the BindingContext inside an ItemTemplate?

    Each instance of the template gets its own item as BindingContext, so bindings read the item's properties.
  3. 3. Which property shows a message when the list has no items?

    EmptyView is displayed when ItemsSource is null or empty, which suits "no results" content.
  4. 4. What breaks virtualization?

    In an unbounded container the list is measured at full height, so every item is created and nothing is recycled.

Summary

  • CollectionView displays ItemsSource through an ItemTemplate, one BindingContext per row, and virtualizes rows.
  • Use ObservableCollection<T> and update it on the UI thread; item property changes need INotifyPropertyChanged.
  • ItemsLayout gives lists, horizontal lists and grids; SelectionMode enables selection; EmptyView, headers and footers handle edge cases.
  • Grouping uses IsGrouped with a list of group objects; RefreshView adds pull-to-refresh.
  • Give the list bounded space and keep templates light.

Next: Input Validation and Forms