Oct 28, 2011

New WPF DataGrid Rows Throw on SelectedItem Binding

In my DataGrid I have the attribute for SelectedItem bound to a property on my ModelView. This works perfectly for existing data, not so much for creating a new row. I don't understand why, but the application first throws an exception about a conversion problem with MS.Internal.NamedObject, whatever that is. Then  I eventually got an exception that had the magic word NewItemPlaceholder in the message. This was the key to finding the solution.  In effect what I think is happening is when a new row is created, the binding to the SelectedItem is failing. I think it may be related to the order in which things are happening. The solutions boils down to telling the system to not bother doing the binding when a new row is encountered.  This requires writing an IValueConverter class and having ConvertBack return DependencyProperty.UnsetValue. Rather that duplicate the fine work of Nigel Spencer, you can get all the details on doing this from his blog post Problems binding to SelectedValue with Microsoft's WPF DataGrid. Thank's Nigel, you're a sanity saver.

About Me

My photo
Tod Gentille (@todgentille) is now a Curriculum Director for Pluralsight. He's been programming professionally since well before you were born and was a software consultant for most of his career. He's also a father, husband, drummer, and windsurfer. He wants to be a guitar player but he just hasn't got the chops for it.