Avalonia Field Guide
About

Module 1 · Lesson 04 of 16

Lists that stay in sync

ItemsSource, ItemTemplate, and SelectedItem are the whole API. ObservableCollection tells the control what changed.

25 minHeadless-tested

Every list control in Avalonia follows the same three properties: what to show (ItemsSource), how to show one row (ItemTemplate), and what is selected (SelectedItem). ListBox adds selection; ItemsControl does not.

src/CourseApp/Lessons/04_Lists/TasksView.axaml:15–45
            <Grid ColumnDefinitions="*,320">
                <Border Classes="card" Padding="0">
                    <StackPanel>
                        <ListBox ItemsSource="{Binding Tasks}"
                                 SelectedItem="{Binding Selected}"
                                 BorderThickness="0"
                                 Background="Transparent"
                                 MaxHeight="330">
                            <ListBox.ItemTemplate>
                                <DataTemplate x:DataType="local:TaskItem">
                                    <StackPanel Spacing="2" Margin="4,6">
                                        <TextBlock Text="{Binding Title}" FontWeight="SemiBold" />
                                        <TextBlock Text="{Binding Project}" Classes="caption" />
                                    </StackPanel>
                                </DataTemplate>
                            </ListBox.ItemTemplate>
                        </ListBox>
                    </StackPanel>
                </Border>

                <StackPanel Grid.Column="1" Margin="16,0,0,0" Spacing="12">
                    <Border Classes="card">
                        <StackPanel Spacing="10">
                            <TextBlock Text="NEW TASK" Classes="kicker" Foreground="{DynamicResource InkMuted}" />
                            <TextBox Text="{Binding NewTitle}" PlaceholderText="What needs doing?" />
                            <Button Content="Add task" Command="{Binding AddCommand}" HorizontalAlignment="Left" />
                        </StackPanel>
                    </Border>

                    <Border Classes="card">
                        <StackPanel Spacing="10">

The template's x:DataType is the item type, not the page's view model. That is the single most common source of "compiled binding failed" errors:

<DataTemplate x:DataType="local:TaskItem">
    <TextBlock Text="{Binding Title}" />
</DataTemplate>

Inside the template, the data context is a TaskItem. To reach the page's view model from a row, bind through an ancestor or expose the command on the item.

Screenshot of the lists lesson sample
The lesson's sample, rendered headlessly at 1280×800. Light and dark are both captured.

Why ObservableCollection

src/CourseApp/Lessons/04_Lists/TasksViewModel.cs
using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;

namespace CourseApp.Lessons.Lists;

public sealed record TaskItem(string Title, string Project);

public partial class TasksViewModel : ObservableObject
{
    public ObservableCollection<TaskItem> Tasks { get; } =
    [
        new("Write the layout chapter", "Field Guide"),
        new("Add a dark theme pass", "Field Guide"),
        new("Test the file picker", "Desktop app"),
    ];

    [ObservableProperty]
    private TaskItem? _selected;

    [ObservableProperty]
    private string _newTitle = "";

    [RelayCommand]
    private void Add()
    {
        var title = NewTitle.Trim();
        if (title.Length == 0)
            return;

        Tasks.Add(new TaskItem(title, "Inbox"));
        NewTitle = "";
        Selected = Tasks[^1];
    }

    [RelayCommand(CanExecute = nameof(CanRemove))]
    private void Remove()
    {
        if (Selected is null)
            return;

        var index = Tasks.IndexOf(Selected);
        Tasks.Remove(Selected);
        Selected = Tasks.Count == 0 ? null : Tasks[Math.Min(index, Tasks.Count - 1)];
    }

    private bool CanRemove() => Selected is not null;

    partial void OnSelectedChanged(TaskItem? value) => RemoveCommand.NotifyCanExecuteChanged();
}

ObservableCollection<T> raises CollectionChanged on add, remove, and reset. The ListBox subscribes and inserts or removes exactly one row. A List<T> gives you nothing: the control has already enumerated it, and the UI will not know that the contents changed.

Do not replace the collection. Tasks = new ObservableCollection<T>(…) in a property setter rebinds the whole control and loses selection and scroll position. Clear and re-add, or mutate in place.

Selection is state, not an event

SelectedItem="{Binding Selected}" is two-way. The sample uses it to decide whether Remove is allowed:

[RelayCommand(CanExecute = nameof(CanRemove))]
void Remove() { … }

bool CanRemove() => Selected is not null;

When Selected changes, OnSelectedChanged calls RemoveCommand.NotifyCanExecuteChanged(), and the button greys out. No if in a click handler, and the rule is testable without a window — which is exactly what the verifier does.

Try it

  1. Add a Filter text box and an ICollectionView-style filtered view; or start simpler with a computed VisibleTasks property and a second ItemsSource.
  2. Add a boolean IsDone to TaskItem (it must be observable) and strike through completed rows with a Style selector.
  3. Sort by project, then by title, and watch selection survive the reorder.

Next: commands, not click handlers.

Files this lesson draws from

  • src/CourseApp/Lessons/04_Lists/TasksView.axaml
  • src/CourseApp/Lessons/04_Lists/TasksViewModel.cs

VerifiedThe verifier adds a task, asserts the count grew, selects an item, removes it, and checks that Remove was disabled beforehand.

Back to top