ListBox Grouping and Virtualization
Virtualization and Sorting
If you’ve also implemented sorting on your collection using the CollectionView sort descriptors, your virtualizing panel should still work. However, there is a minor bug that should be fixed.
We need to update our collection of INestedPanel references in the grouping panel. When you perform sorting, new instances of GroupingItem and your inner panels are being added to the ListBox’s visual tree, while the INestedPanels that you had references to are being removed from the tree. We should remove our references to these orphaned panels.
To do this, I overrode OnVisualChildrenChanged() in the grouping panel. This method gets called when the visual children in an element are added or removed. Whenever visual children are removed, I called this.IsAncestorOf() on each INestedPanel reference in my collection to see if it was still a part of the grouping panel’s visual tree. If not, I marked that reference to be removed from my collection.
All of this happened asynchronously in context of Dispatcher.BeginInvoke() with Background priority. The reason I did this was to make sure these operations did not interfere with operations that could disrupt responsiveness to the user, such as the layout pass, etc. It was to also ensure the collection of references was being modified in a safe fashion.
That’s it, you should now have a databound ListBox that has virtualization, grouping, and sorting. While this was a deep learning experience for me, it wasn’t exactly an enjoyable.
Hopefully this guide has been helpful, and at least made your experience with virtualization in WPF more enjoyable
This entry was posted on February 22, 2008 at 9:04 pm and is filed under WPF. You can subscribe via RSS 2.0 feed to this post's comments.
Tags: grouping, lazy-loading, ListBox, panel, scrolling, virtualizing
You can comment below, or link to this permanent URL from your own site.
July 9, 2009 at 11:10 am
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.