Wednesday, January 29, 2014

#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.

Inline image 1