ListBox
The ListBox
is an ItemsControl
which displays items in a multi-line list box and allows individual selection.
The items to display in the ListBox
are specified using the Items
property. This property will often be bound to a collection on the control's DataContext
:
<ListBox Items="{Binding MyItems}"/>
Customizing the item display
You can customize how an item is displayed by specifying an ItemTemplate
. For example to display each item inside a red border with rounded corners:
<ListBox Items="{Binding MyItems}">
<ListBox.ItemTemplate>
<DataTemplate>
<Border Background="Red" CornerRadius="4" Padding="4">
<TextBlock Text="{Binding}"/>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Containers
Each item displayed in a ListBox
will be wrapped in a ListBoxItem
- this is called the container. The container hosts the content specified in the ItemTemplate
but it is not part of the ItemTemplate
itself. It is the container that contains the logic for displaying selected items.
Sometimes you will want to customize the container itself. You can do this by including a style targeting ListBoxItem
in the ListBox
:
<ListBox Items="{Binding Items}">
<ListBox.Styles>
<!-- Give the ListBoxItems a fixed with of 100 and right-align them -->
<Style Selector="ListBoxItem">
<Setter Property="Width" Value="100"/>
<Setter Property="HorizontalAlignment" Value="Right"/>
</Style>
</ListBox.Styles>
</ListBox>
In WPF and UWP this is done via the ItemContainerStyle
- this property does not exist in Avalonia; you should use the method outlined above.
Selection
There are several properties related to selection on ListBox
:
It is recommended that you only bind one of the SelectedIndex
, SelectedItem
, SelectedItems
or Selection
properties.
SelectionMode
Controls the type of selection that can be made on the ListBox
:
Property | Description |
---|---|
Single | Only a single item can be selected (default) |
Multiple | Multiple items can be selected |
Toggle | Item selection can be toggled by tapping/spacebar. When not enabled, shift or ctrl must be used to select multiple items |
AlwaysSelected | An item will always be selected as long as there are items to select. |
These values can be combined, e.g.:
<ListBox SelectionMode="Multiple,Toggle"/>
SelectedIndex
Exposes the index of the selected item, or in the case of multiple selection the first selected item. You will often want to bind this to a view model if your list SelectionMode
is set to Single
.
<ListBox SelectedIndex="{Binding SelectedIndex}"/>