Monday, April 10, 2006

Windows.Forms databinding doesn't work for domain objects.

As you can see from one of my recent posts, I'd like to use databinding in our application to bind our domain objects to our forms. It's really boring having to write lots of code to shunt domian object properties to gui control properties and back again. The data binding built in to Windows.Forms at first looks quite promissing. You can write stuff like this:
nameTextBox.Bindings.Add(new Binding("Text", myCustomer, "Name"))
... which will handle all the shunting of values to and from your domain object. The problem comes when you want to validate what the user types in. What I'd really like to do is to throw an exception from my domain object's property setter and then have some neat way of wiring it up to a Windows.Forms.ErrorProvider. Instead the data binder simply catches the exception and refuses to tab away from the control. Your user has no idea what's wrong or what they need to do to fix it. OK, so we'll just extend the Binding class to override the bit that catches the exception. Microsoft have ruled this out by making all the internal workings of the Binding class private and there's no extensible mechanism for plugging in your own Binding implementation. There's a good post by Martin Robins on all this. I understand that the data binding has been fixed in dotnet 2.0, but we're still stuck with 1.1 here so there's nothing for it but to spin our own crappy event driven solution to notify validation exceptions.

No comments: