Tag Archives: Silverlight

Windows Phone (regular Silverlight and WPF too) ListBox virtualization rendering problems

I am currently working on a simple Windows Phone game and came across a peculiar problem regarding the rendering of controls inside a data bound ListBox. Whenever I had more items than could be displayed on the screen, the ListBox would automatically create a nice scrollbar, but when I scrolled down items start rendering odd. You might for instance see strange spacing between item texts, or items rendered in spots where another item should be.

After some googeling (actually quite a lot of googeling) I found out this has something to do with ListBox Virtualization. What happens is that only controls that are visible on screen get rendered to save memory and other precious resources (see more info on that here). The ListBox accomplishes this by using a VirtualizingStackPanel control. Not all controls work well with virtualization, and the control I created for my application was one of those controls.

Since I only wanted to display about 20 or so items in the ListBox and not thousands, I preferred my ListBox not to virtualize its contents. There are a few ways to do this:

Disabled scrolling

You can disable scrolling on the ListBox and wrap it in a dedicated ScrollViewer control:

        <ListBox Name=”myListBox” ScrollViewer.VerticalScrollBarVisibility=”Disabled”>

This will render the entire ListBox control as if it had all the space on the screen, and no virtualization is performed. The ScrollViewer takes care of the scrolling instead of the ListBox.

Changing the ItemsPanel of the ListBox

This looks to be the preferred way to disable virtualization of the ListBox. Templating allows you to replace the VirtualizingStackPanel with a regular one:

            <ListBox Name=”myListBox”>
                        <StackPanel />

And there you go, no more virtualization, no more rendering problems.