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 :-)

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.