Thursday, December 6, 2012

Apparent binding problems with NotSupportedException in PresentationFramework

I ran into this problem twice over the last couple weeks. Perhaps if I write an article, it'll help my future self (and just perhaps someone else) not spend so much time on it...

I put together a simple WPF form with a ListView. The ListLiew's View contained a GridView with columns bound to a POCO's properties. This was all done in XAML. In the constructor, I created an ObservableCollection to contain the objects and set it to the ListView's ItemsSource property. An event fired when interesting things happened. The event handler created the POCO object, set its properties and added it to the collection.

Everything should have worked.

However, when items were added to the collection, the debug window reported:
A first chance exception of type 'System.NotSupportedException' occurred in PresentationFramework.dll
Over the years, I've found data binding to be a challenge to get working. Part of the problem is it's mostly silent when it fails. So, data simply doesn't show up where it's expected with no indication as to why. Because of this, I assumed this is where the problem lay and spent significant time trying to figure out what was happening.

After quite a while I realized the event handler was called from a non-UI thread. I changed the line that added objects to the collection from:
ListViewDetails.Add(detailData);
to:
Dispatcher.Invoke((Action)(() =>
    ListViewDetails.Add(detailData)));
and everything worked properly. A simple solution once I realized what was wrong.

It'd be really nice if the debug window would output the exception message and not just the type. This would have told me immediately what was wrong and I wouldn't have spent so much time going down a dead-end road.