Thursday, April 30, 2009

WPF DataGrid binding weirdness

Recently I had an object with a read-only property that I wanted to bind to a WPF DataGrid column. I expected an easy Binding="{Binding Path=MyProperty}" to accomplish it. However, when I made this change and tried to display the data at run-time, I got a bunch of exceptions:
A TwoWay or OneWayToSource binding cannot work on the read-only property 'MyProperty' of type 'MyObject'.
"Ok," I thought, "just change the binding's Mode."

So I assigned the value OneWay to Mode in the binding: Binding="{Binding Path=MyProperty, Mode="OneWay"}.

Same thing. No difference. Huh!?!?

After a bit of head scratching and digging through search results, I set the IsReadOnly property on the column to true.[1] That worked!

I removed the Mode assignment from the binding. It still worked!

Apparently, the DataGrid ignores the binding mode and sets it to what it thinks it should be, regardless of what it's told. Frustrating.
1. This post on GenericError.com pointed me in the right direction.