WTF Moment: Data Binding Errors in ListBoxes
Let’s say you have a ListBox that is data-bound to an ObservableCollection and set up similar to this:

Also, assume you’ve implemented sorting on your collection using the CollectionView representing your data bound items.
Can you guess what’s wrong?
When you sort the items (you’re really sorting UI elements representing your data), a data binding error occurs for every item in the collection. From what I can ascertain from the cryptic error messages, the runtime can’t find the instance of the ItemContainerStyle associated with each item.
As you probably already know, data binding errors are really exceptions. Remember, there is overhead involved when exceptions get thrown not only because an object is being constructed, but because the callstack is getting unwound somewhere.
This is an actual error that was happening in Jing’s History bin. Although I don’t have hard data to validate my claims, these data binding errors were causing a perceivable hit to performance when sorting. When you sort the UI elements representing your items in a collection view, all the UI elements are being destroyed and regenerated (if you don’t believe me, set break points in the debugger to see for yourself). And with a data binding error being thrown for each item, sorting becomes proportionally worse as you add more items to the collection.
The work-around for this is simple, but in all honesty I have no idea why it works. All you have to do is set the ListBox’s GroupStyle. That’s it, no more data binding errors when sorting your collection. If you don’t need grouping, just make the GroupStyle hidden.
Someday I’ll get off my lazy butt and ask Microsoft why this works. Until then, this quirk with the ListBox still makes me think, “WTF?”.
This entry was posted on January 30, 2008 at 3:02 pm and is filed under WPF. You can subscribe via RSS 2.0 feed to this post's comments.
Tags: data binding, grouping, ListBox
You can comment below, or link to this permanent URL from your own site.