The WPF ListBox Control and List Selection Options
The WPF ListBox control is one of the simplest and most basic list controls available in the Windows Presentation Foundation of Microsoft NET Framework 3.0 and higher. It lets you make a series of items available for selection in a list, with multiple items visible and selectable at the same time. Within this relatively simple framework, the WPF ListBox provides considerable flexibility, making it a remarkably versatile tool.
If you’re interested in finding out more about developing for Microsoft Windows, by the way, there are a variety of online classes available.
The Basic ListBox
At its most basic, the ListBox simply lists a series of text items, one above the other. When the user clicks on an item, it is highlighted, and the SelectedItem property returns that item. The following XAML sample creates a basic ListBox with six items listed:
<Window x:Class="ListBoxTest.BasicBox" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Basic ListBox" Height="150" Width="325"> <ListBox> <ListBoxItem>First Thing</ListBoxItem> <ListBoxItem>Second Thing</ListBoxItem> <ListBoxItem>Third Thing</ListBoxItem> <ListBoxItem>Thing With Long Name</ListBoxItem> <ListBoxItem>Thing With Much Longer Name That Maybe Won't Fit</ListBoxItem> <ListBoxItem>Last Thing</ListBoxItem> </ListBox> </Window>
In the above sample, the item with the long name will fit the box. If you make the box much narrower (by setting the width to something lower than 325 pixels), or the name of the item longer, the Basic ListBox window will have scrollbars.
In order for the WPF ListBox control to be useful, of course, you need to be able to do something with the selected item. The simple way to do this is with the SelectedItem property. To test SelectedItem, let’s change the example a bit:
<Window x:Class="ListBoxTest.BasicBox" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Basic ListBox" Height="200" Width="325"> <StackPanel Orientation="Vertical"> <ListBox Name="BasicBox" Height= "100" > <ListBoxItem>First Thing</ListBoxItem> <ListBoxItem>Second Thing</ListBoxItem> <ListBoxItem>Third Thing</ListBoxItem> <ListBoxItem>Thing With Long Name</ListBoxItem> <ListBoxItem>Thing With Much Longer Name That Maybe Won't Fit</ListBoxItem> <ListBoxItem>Last Thing</ListBoxItem> </ListBox> <TextBox Width="295" Margin="5,15,0,0" HorizontalAlignment="Left"> <TextBox.Text> <Binding ElementName="BasicBox" Path="SelectedItem.Content"/> </TextBox.Text> </TextBox> </StackPanel> </Window>
Stack and Show
We’re going to add a TextBox control to display the output, so we need to tell the Basic ListBox window how to display more than one control. We do this by enclosing both the ListBox and the TextBox in the StackPanel control, like this:
<StackPanel Orientation="Vertical"> ... stuff ... </StackPanel>
We expand the window and give the ListBox a name (“BasicBox”) so that it can be identified by the other controls. Then we add the TextBox, bind it to the ListBox (using the name that we just gave it) and tell it to display the Content (the selected text itself) of SelectedItem. Now when you click on an item, the text will appear in the TextBox.
Of course, as a well-trained. professional programmer, you’ll want your ListBox selection to do more than this; but the SelectedItem property is the foundation for most of the things that you will be doing with a single ListBox selection.
Notice that we said “a single ListBox selection.” You may have been wondering whether it’s possible to select more than one item in a ListBox — it is possible, and you can access multiple selected items using the SelectedItems property.
Before we look at SelectedItems, however, let’s take a look at the way that you enable multiple selections:
<ListBox Name="BasicBox" SelectionMode="Extended" Height= "100" > ... items ... </ListBox>
The options for SelectionMode are Extended (which allows multiple selections using the Shift and Ctrl keys), Multiple (which allows multiple selections without holding down any key), and Single (the default, which does not allow multiple selections). In both Extended and Multiple mode, the user can click (or Shift/Ctrl + click) on an item a second time to deselect it.
Use Those Items
With the Extended or Multiple modes, you can either use the SelectedItem property to return the first item from those that are currently selected, or use the SelectedItems property to return all of the items currently selected in the form of a collection of the type System.Collections.IList.
Since SelectedItems is a collection, it is considerably more complex than the SelectedItem property. They key properties to keep in mind when using SelectedItems with a ListBox are Count, which returns the number of elements, and Item, which returns the element at a specified index. In practice, you would use the code-behind (the functional code, written in C++,C#, VB, etc., as opposed to the XAML UI markup code which we have been showing you here) to handle the data returned by SelectedItems.
But Wait – There’s More!
The ListBox control is part of the ItemsControl class of controls, and it inherits some important properties from ItemsControl. Among these are text formatting, and the ability to list items besides simple text strings.
There are times when plain text is nice, but there are also times when you will want to format it:
<ListBoxItem Background="DarkGreen" Foreground="LightPink" FontFamily="Courier New" FontSize="14" FontStyle="Italic">First Thing</ListBoxItem> <ListBoxItem Background="LightGreen" Foreground="DarkRed" FontFamily="Calibri" FontSize="14" FontStyle="Oblique" FontWeight="ExtraBold">Second Thing</ListBoxItem> <ListBoxItem Background="Red" Foreground="SpringGreen" FontFamily="Arial Unicode" FontSize="16" FontStyle="Normal" FontWeight="Medium">Third Thing</ListBoxItem> <ListBoxItem Background="Gold" Foreground="CornflowerBlue" FontFamily="Consolas" FontSize="14" FontWeight="Black" >Thing With Long Name</ListBoxItem> <ListBoxItem Background="Blue" Foreground="OrangeRed" FontFamily="Arial" FontSize="13" FontWeight="Black" FontStretch="UltraCondensed">Thing With Much Longer Name That Maybe Won't Fit</ListBoxItem> <ListBoxItem Background="Yellow" Foreground="Red" FontFamily="Times New Roman" FontWeight="Black" FontSize="11" >Last Thing</ListBoxItem>
Needless to say, the output of this example is not a thing of beauty, but it does show what you can do with text formatting in a ListBox. Note that some features (such as FontStretch) do not apply to all fonts. And remember — if you’re working as a professional programmer producing applications for commercial release, the output should look tasteful.
Not Just Text
In practice, if you’re actually interested in graphic effects, the built-in font formatting available in Windows development is rather limited, since it actually is meant for tasteful presentation of text. A ListBox control can list graphics as well as text. So, for example, if you wanted to list “Sakura” in Japanese text, with an appropriate cherry-blossom background, you could include it as a graphic item:
<ListBoxItem > <Image x:Name="sakura" Source="sakura.png" ></Image> </ListBoxItem>
In practice, you might use a StackPanel control with Horizontal orientation to place the image and accompanying text on the same line, as well as setting the size of the image.
You can also place built-in graphic objects (such as rectangles, circles, and ellipses), standard UIElement objects, and Panel controls that contain UIElement objects in a ListBox.
Whether you use simple, unformatted text strings or something more visually striking in a ListBox, there are some very basic ListBox properties and methods which you will probably find yourself using frequently, including those which affect the selection and visibility of list items.
The SelectedIndex property, for example, sets the item initially selected in a list:
<ListBox SelectedIndex="1"> <ListBoxItem>Item One (index 0)</ListBoxItem> <ListBoxItem>Item Two (index 1)</ListBoxItem> <ListBoxItem>Item Three (index 2)</ListBoxItem> </ListBox>
Since SelectedIndex counts from 0, this makes “Item Two (index 1)” the initially selected item.
For Extended mode, you can also use AnchorItem to get or set the list item which is initially selected.
If your ListBox includes more than a few items, and if you have set the SelectionMode property to Extended or Multiple, you may want to give the user the option to select all of the items at once. To do this, you can use the SelectAll method, typically by means of a button or other GUI option which uses SelectAll when clicked. Note that if you have set the SelectionMode property to Single, SelectAll will produce a NotSupportedException error.
Whether or not you use the SelectAll method, if your list includes a large number of multiply-selectable items, you probably will want to use the UnselectAll method to give users a way of deselecting multiple selections, particularly if the list scrolls, so that not all selected items are visible.
Setting the Selections
There may be times when you want to automatically select several items in a multiply-selectable list. To do this, you can use the SetSelectedItems method to set the selection to a collection of items. You could, for example, have two ListBoxes — one with a long list of selections (vacation destinations, for instance), and the other with a shorter list of multiple selection options (such as tour packages). When a user selects a tour package, the locations included in the tour would automatically be selected.
Want to find out more about the WPF ListBox, and Microsoft programming? There’s always room for good programmers, whether it’s in VBA for applications, in C#, or in any of the other fields where Microsoft programming skills are in demand.
Empower your team. Lead the industry.
Get a subscription to a library of online courses and digital learning tools for your organization with Udemy for Business.