ListBox

Selectable list with keyboard navigation, ObservableCollection binding, and selection indicators.

Overview

The ListBox control extends Selector and supports keyboard navigation, mouse selection, and two-way SelectedItem binding. Items can be provided via ItemsSource binding to an ObservableCollection.

<ListBox ItemsSource="{Binding MenuItems}"
         SelectedItem="{Binding SelectedMenuItem, Mode=TwoWay}" />

<Button Text="Add Item" Command="{Binding AddItemCommand}" />
<Button Text="Remove" Command="{Binding RemoveItemCommand}" />

<!-- Custom UserControl with x:Class -->
<sample:ActivityLogControl ItemsSource="{Binding LogEntries}" />

ViewModel (C#)

public class ListsViewModel : ViewModelBase
{
    public ObservableCollection<string> MenuItems { get; } =
        ["Dashboard", "Messages", "Settings", "Profile", "Help"];

    public string? SelectedMenuItem
    {
        get;
        set
        {
            if (SetProperty(ref field, value))
                SelectionText = value != null ? $"Selected: {value}" : "No selection";
        }
    }

    public ICommand AddItemCommand => field ??= new RelayCommand(() =>
    {
        MenuItems.Add($"Item {++_counter}");
    });

    public ICommand RemoveItemCommand => field ??= new RelayCommand(() =>
    {
        if (SelectedMenuItem != null)
            MenuItems.Remove(SelectedMenuItem);
    });
}

Key Concepts