ListBox

Introduction

The ListBox control provides a scrollable list of ListBoxItems for displaying and selecting from a list.

Code Example: Adding a ListBox

The following code adds items to a ListBox when a button is clicked. When an item is added, ScrollIntoView is called so the item is shown.

var listBox = new ListBox();
this.Root.Children.Add(listBox.Visual);
listBox.X = 50;
listBox.Y = 50;
listBox.Width = 400;
listBox.Height = 200;

var button = new Button();
this.Root.Children.Add(button.Visual);
button.X = 50;
button.Y = 270;
button.Width = 200;
button.Height = 40;
button.Text = "Add to ListBox";
button.Click += (s, e) =>
{
    var newItem = $"Item @ {DateTime.Now}";
    listBox.Items.Add(newItem);
    listBox.ScrollIntoView(newItem);
};

Selection

ListBox items can be selected. The ListBox class provides a number of ways to work with the selection.

Selection can be set by index:

listBox.SelectedIndex = 0;

Item can also be selected by the reference itself, assuming the referenced item is part of the list box:

listBox.SelectedObject = "English";

Whenever the selection changes, the SelectionChanged event is raised:

listBox.SelectionChanged += (sender, args) =>
{
    System.Diagnostics.Debug.WriteLine($"Selected item: {listBox.SelectedObject}");
};

Last updated