ListBoxItem

Introduction

ListBoxItem is a selectable control used in the ListBox control or controls which contain a ListBox (such as ComboBox). ListBoxItem instances can be manually instantiated just like any control, or may be instantiated internally by the ListBox control.

Layout Requirements

The ListBoxItem control has no requirements – an empty container is sufficient.

TextInstance

The ListBoxItem control can optionally include a Text instance named TextInstance. Setting the ListBoxItem control’s Text property changes the TextInstance’s displayed string.

Creating ListBoxItems

ListBoxItem instances are typically created and added to a ListBox. For more information and examples on working with ListBoxItem instances in a ListBox, see the ListBox page.

Inheriting from ListBoxItem

The default ListBoxItem expects that the Gum runtime used as the visual has a Text object called TextInstance. The default ListBox implementation assigns the text on the TextInstance according to its matching object’s ToString.

For example, consider the following code:

Internally the ListBoxItem class calls ToString to get the displayed string.

While this behavior is simple to use, some lists may need to display more complex data.

For this example consider a racing game with a list of cars. We can create a CarListItem in Gum to display information about cars in a player’s garage.

Notice that this list item does not have a single Text but instead four – for displaying the year, make and model, horsepower, and weight. This shows that list items can contain anything to display the necessary information or decoration.

For this example we’ll use a data class called CarData, defined as shown in the following code:

We need to create logic to assign the values from CarData instances to the text values in the CarListItem Gum component. For this we can create a new class which inherits from ListBoxItem, as shown in the following code:

Finally, we can get our ListBox instance and assign the desired Gum and Forms types, as shown in the following code:

Now if we add any objects that are not ListBoxItems, the ListBox will internally use the CarListBoxItem control and assign a CarListItemRuntime Gum runtime for its visual.

For example, the following code could be used to populate the list box:

This creates a list of our cars.