#996 – Turning off UI Virtualization in a ListBox

By default, a ListBox uses UI virtualization, creating UIElements for each list item only as they are scrolled into view.  This is normally what you want, since using UI virtualization improves the performance of the ListBox when it contains a large number of items.

You can, however, disable UI virtualization by setting the VirtualizingPanel.IsVirtualizing property on the ListBox to false.

In the example below, we load two ListBox controls with a list of 100 numbers.  We turn off UI virtualization for the second ListBox and then examine the visual tree of each ListBox.

        <ListBox Name="lbDefault" Margin="15,10" Width="70" Height="200"
                 ItemsSource="{Binding NumberList}" />

        <ListBox Name="lbNoVirtualization" Margin="15,10" Width="70" Height="200"
                 VirtualizingPanel.IsVirtualizing="False"
                 ItemsSource="{Binding NumberList}" />

In the ListBox that does use UI virtualization, the visual tree shows that it contains only a small number of ListBoxItems.
996-001
In the second ListBox, where we turned off UI virtualization, the visual tree contains a ListBoxItem for each of the 100 items in the source data.

996-002

Advertisement

#995 – ListBox Uses UI Virtualization by Default

List-based controls in WPF are comprised of a panel that contains a child UIElement for each item in the list.  The visual tree for a ListBox includes a VirtualizingStackPanel as a container for a series of ListBoxItem instances.  The ListBoxItem is the user interface element that renders an item from the list.

994-002

When a list contains a large number of items, it would take a long time and a large amount of memory to create a ListBoxItem for each element in the list.

To improve performance, a ListBox uses UI virtualization by default.  UIElement-based objects are created only for the items currently being displayed in the list.  New UIElements are then created as additional items are scrolled into view.

We can see this by binding a ListBox to a collection containing 1,000 elements and then looking at its visual tree.  ListBoxItems have been created for only the first few items.

995-001