Sunday, August 26, 2012

WPF DataGrid and 'Random' ArgumentException

WPF's DataGrid class seems to have an odd problem. If you put a DataGrid in a ScrollViewer, and if you bind a collection of a type with a specific kind of GetHashCode() implementation, and if you edit data in the grid twice, an ArgumentException will likely be thrown by clicking the data grid a third time. I say "likely" because it sometimes didn't occur on the third attempt. Here's an example stack trace:



I could not find source code for InternalSelectedItemsStorage's constructor, but it probably calls GetHashCode() to generate a dictionary key. The DataGrid problem is resolved by changing the GetHashCode() implementation so that it gives the same return value even if the name or price of an object changes.

Here are two examples (one bad, one better) of GetHashCode() implementations.