How a VirtualizingStackPanel works

A VirtualizingStackPanel is recommended instead of a regular StackPanel when you have a large number of scrollable items.

The reason for this is that a regular scrolling StackPanel will render every single UI element in the list when its loaded, including the ones that are not visible, while a VirtualizingStackPanel will only render the visible UI elements. When you scroll a VirtualizingStackPanel it will re-use the existing elements instead of creating new ones, and simply replaces the DataContext behind them.

For example, if you have an VirtualizingStackPanel with 100,000 items, and only 10 are visible at a time, it will render about 14 items (extra items for a scroll buffer). When you scroll, the DataContext behind those 14 controls gets changed, but the actual controls themselves will never get replaced. In contrast, a regular StackPanel would actually render 100,000 items when it gets loaded, which would dramatically decrease the performance of your application.

To see a VirtualizingStackPanel in action, create one that has a bunch of TextBoxes that are not bound to anything. If you type Text in TextBox #1, and that TextBox.Text is not bound to anything, then the Text will stay in the top TextBox when you scroll the list because the control is getting re-used. If you bind TextBox.Text to a value, then the DataContext will change when you scroll, which will replace the displayed Text.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: