BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Windows Presentation Foundation
.NET 4.0+

WPF Selection Controls - ListBox

The seventieth part of the Windows Presentation Foundation Fundamentals tutorial looks at another of the WPF selection controls. This article examines the ListBox, which allows users to select from a large number of options.

Multiple Selection

ListBox controls can be configured to allow multiple selections. To permit this, you can change the selection mode using the SelectionMode property. Three possible options are available, each defined in the SelectionMode enumeration. The values are:

  • Single. The default option, permitting only a single selection.
  • Multiple. When set to Multiple, the user can toggle the selections by clicking items. Any number of items may be selected.
  • Extended. The extended mode allows multiple selection in a manner similar to that of programs such as Windows Explorer. Clicking one item selects it and deselects any others. Holding the Shift key whilst clicking allows a group of contiguous items to be selected. Holding the Ctrl key lets you choose multiple items or groups individually.

To demonstrate, change the ListBox selection mode to Multiple by changing the XAML, as follows:

<ListBox Name="MyList" SelectionMode="Multiple">
    <ListBoxItem>Red</ListBoxItem>
    <ListBoxItem>Orange</ListBoxItem>
    <ListBoxItem>Yellow</ListBoxItem>
    <ListBoxItem>Green</ListBoxItem>
    <ListBoxItem>Blue</ListBoxItem>
    <ListBoxItem>Indigo</ListBoxItem>
    <ListBoxItem>Violet</ListBoxItem>
</ListBox>

The properties defined in the Selector class do not permit you to identify more than one selection. Instead, you can use the SelectedItems property to get a list of the selected items. To demonstrate, modify the code for the button's click event. The following method loops through the selected items and shows each in a message box.

private void Button_Click(object sender, RoutedEventArgs e)
{
    if (MyList.SelectedItems.Count == 0)
    {
        MessageBox.Show("No selection");
    }
    else
    {
        foreach (ListBoxItem selected in MyList.SelectedItems)
        {
            MessageBox.Show(selected.Content.ToString());
        }
    }
}

A second way to determine or set the selections is using the ListBoxItem objects in the Items property. ListBoxItem includes a Boolean property, IsSelected, which is true if the user has selected the item. The following sample code uses this property instead of the SelectedItems list.

private void Button_Click(object sender, RoutedEventArgs e)
{
    if (MyList.SelectedItems.Count == 0)
    {
        MessageBox.Show("No selection");
    }
    else
    {
        foreach (ListBoxItem item in MyList.Items)
        {
            if (item.IsSelected) MessageBox.Show(item.Content.ToString());
        }
    }
}
12 June 2014