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.

1 comment:

Comments are welcome but I do moderate them. This is simply to keep things wholesome for general family viewing. By default, comments will be accepted. The few things that will cause a comment to be rejected are:

1. It is too long even though it may be well-written and make interesting points. It's supposed to be a comment, not an essay. If you have that much to say, write a blog article and backlink to me.

2. It is nasty, impolite or uses language that is unacceptable.

3. It includes a a link that has a typo or is broken in some other way.

4. It should have been sent as an e-mail since it is clearly addressed to me and does not appear to have been intended for other readers.

5. It is blatantly self-promotional. This does not mean it can't be self-promotional at all, but it should add some value over an above the marketing.