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.
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:
Item can also be selected by the reference itself, assuming the referenced item is part of the list box:
Whenever the selection changes, the SelectionChanged event is raised:
Customizing with VisualTemplate
The VisualTemplate lets you customize the type of ListBoxItem created for the ListBox. The following code shows how to assign a VisualTemplate to a runtime object named CustomListBoxItemRuntime:
The VisualTemplate class can optionally pass a parameter representing the item in the list box. This can be used to create different types of items based on the object added. For example the following code would compare the passed object as an integer to whether it is greater than 100 and returns a different item depending on this result:
Customizing Displayed Property with ListBoxItemFormsType
By default the ListBox calls ToString on each item. This is usually okay if you are dealing with primitive types. For example, the following code adds sequential integers to a ListBox:
Often you may want to add a list of items which should not use their ToString method. For example you may have a list of IDs which represent weapons in a dictionary. The display can be customized by inheriting from ListBoxItem as shown in the following code:
Last updated
Was this helpful?