Monday, February 7, 2011

Faster Controls with UI Virtualization in WPF

A very useful feature in WPF for making faster and interactive UIs is UI virtualization. Let's say, in your WPF application, you have a ComboBox with 10,000 elements in it. When you will click the ComboBox to expand it, it will take quite some time before actually the ComboBox's available options will be displayed in a drop down for selection. The reason is simple, loading 10,000 UI elements in WPF's visual tree naturally takes some time. One thing to keep in mind is that whether your combo box contains 10K element or 100K elements, user will be looking at a very limited number of options at one instance of time. For example if you expand a combo box, at one time you will only be looking at approximately 25 elements. Even if at one time we see only limited amount of items, WPF loads all the item in visual tree when you click expand button and it takes memory and time. By enabling UI virtualization in your ComboBox, WPF will create only those elements in memory which you can see at one time. This will make combo box expand in no time and as a result even if your combo box contains 10K elements, WPF will take no time to expand it. As you will move the scroll bar down to see more items in ComboBox, WPF will dynamically dispose the elements which will go out of the view as a result of scrolling and will create & load new items in ComboBox accordingly. 
Some controls uses UI Virtualization by default like ListBox and ListView but some controls don't for example ComboBox. You can use following XAML to enable UI virtualization in a combo box and similarly in any control you want.

   1:  <ComboBox ItemsSource="{Binding Path=Collection}">
   2:       <!--comment ComboBox.ItemsPanel below to see how much time WPF takes to load this ComboBox without UI virtualization-->
   3:       <ComboBox.ItemsPanel>
   4:            <ItemsPanelTemplate>
   5:                 <VirtualizingStackPanel />
   6:            </ItemsPanelTemplate>
   7:        </ComboBox.ItemsPanel>
   8:  </ComboBox>
I have uploaded an application which you can use to see the difference in loading time with and without UI virtualization. You can download this application from here. Comment the ComboBox.ItemPanel in XAML to note the time it takes without UI Virtualization and uncomment ComboBoc.ItemPanel to note time it takes with UI Virtualization.

1 comment:

  1. I have a strange issue as in when i made virutalzation true, i have a checkbox on top of the grid to check all the checkboxes in the grid. But when i see the count of checked items before and after scrolling the view, it differs. So is there anyway we can achieve this using virutalization. Or we should get rid virtualization and think of another solution. We saw that without virutalization property the grid loads very slow. Any thoughts.

    ReplyDelete