ListBox Grouping and Virtualization

I would like to give a big “Thanks!” to Microsoft’s Ben Carter for providing me the high-level solution to this difficult problem, and making work over the past month a little bit less frustrating.

Update 3/3/2008: I have reworked my solution to prevent virtualization from not working when sorting the ListBox with the CollectionView sort descriptors. I apologize for any inconvenience this may have caused.

Previously, I discussed how turning on grouping in a ListBox would prevent a virtualizing panel from, well, performing virtualization or lazy-loading of UI elements. When you turn grouping on, your visual tree should look similar to:

groupingvisualtree.png

When you turn on grouping, you are silently adding a StackPanel to your window’s visual tree, which is the one that communicates with the parent ScrollViewer object. Also, note how the virtualizing WrapPanel is wrapped inside a GroupingItem instance. Fixing this requires you to write a custom panel for ListBox.GroupingStyle.

The idea is the panel you write for grouping (to replace the StackPanel) will communicate with the virtualizing panel that’s being used in ListBox.ItemsPanelTemplate. The inner panel should be able to query the outer panel for the viewport size on each layout pass so it knows which children it needs to realize/unrealize. Conversely, because the outer panel is the one controlling scrolling, it needs to call the appropriate methods in the inner panel any time its scroll offsets change.

However, the sequence of events in this can be tricky so I will explain at a high level how I implemented this (hack) fix. Since I did this under company time, I cannot share my source code with you. Sorry.

Assumptions

You have implemented a virtualizing panel and want it to work with ListBox grouping.

The panel I wrote for grouping mimics a vertically oriented StackPanel, but you should write one to suit your needs (if you have VS 2008, you can look at Microsoft’s panel source code to make things easier).

Explore posts in the same categories: WPF

Pages: 1 2 3 4 5 6 7

Tags: , , , , ,

You can comment below, or link to this permanent URL from your own site.

One Comment on “ListBox Grouping and Virtualization”

  1. Luke Says:

    Great blog post! Can you please provide more details how you reworked your solution to support sorting? I am having trouble with virtualization when grouping is enabled and can’t seem to solve this issue.


Comment:

You must be logged in to post a comment.