The Initially Selected Item when Binding to a Grouped ICollectionView

September 18, 2008

I found a bug in WPF today.  That doesn’t happen very often, but today was one of those days.  If you bind a ListBox to an ICollectionView that has one or more PropertyGroupDescriptions in its GroupDescriptions collection, the initially selected item’s IsSelected property is set to true.  This might not sound like a bug, but it turned out to be one of those issues that took an hour of my life away.  This blog post shows the workaround I came up with.

Suppose you have a collection of PersonViewModel instances, where the class is defined as:

Also suppose that you have these resources set up, and they are applied to the ListBox that displays the list of PersonViewModel objects:

The ListBox is declared as:

The UI also has another ListBox that is not bound to a grouped collection view, and also, beneath the ListBoxs, a TextBlock that shows the selected PersonViewModel’s Bio property. When you run the app, it looks like this:

If you select Steve Smith from the left ListBox, the UI updates accordingly:

However, if you then select Dave Brown again from the right ListBox (the one bound to grouped data), watch what happens:

Yikes!!  The left ListBox and Bio area did not update.  Why not?  Because it turns out that the initially selected item in a ListBox bound to a grouped ICollectionView has its IsSelected property set to true, as a local value.  According to rules of WPF, a local value takes precedence over the value provided by a binding.  So, the binding established on the ListBoxItem’s IsSelected property is overwritten by a local value.

Until Microsoft fixes the bug I reported about this we are stuck using a workaround.  Here’s what I came up with, as seen in the window’s code-behind file.

You can download the demo project here.  This application was compiled in Visual Studio 2008 against .NET 3.5 SP1.  You must change the file extension from .DOC to .ZIP and then decompress it.