I’m really falling in love with the whole .Net databinding scheme… but apparently there are still a couple of gotchas out there. Let’s say that my class has a member variable of type double named Susan. Well there seems to be no immediate way to bind Susan to a text box SusanText because the binding looks something like this
SusanText.DataBindings.Add("Text",datasource,"Property")
And Susan isn’t a property. So I can make Susan a public property, but that kinda stinks… what if I want to keep Susan hidden? (I guess I could make Susan a public property of a private instance of some internal class… but that’s a lot of work for a little double.) However, I have a bigger problem coming up, so for the sake of argument let’s go ahead and do this:
private double Susan_;
public double Susan{ get; set;}
...
SusanText.DataBindings.Add("Text",this,"Susan")
Then everything initially seems to work as expected. If I alter SusanText, Susan is altered correspondingly. However, the problem arrises when I alter Susan directly. I would like for SusanText to be automatically updated. So I suspect that I need to make Susan a subclass of double that implements some sort of IBindable interface, so that if Susan is databound to SusanText that the appropriate Events are registered and Susan will notify others if she is modified.
What is the simplest way to make Susan do what I want her to do?
Thanks!
DataBinding expects the class it’s bound to to raise
INotifyPropertyChangedto indicate that a value has been altered and needs to be re-read; unfortunately implementing this still requires some manual coding (or something like PostSharp to IL-weave the necessary code).So, to support databinding you can’t use automatically implemented properties, or be bound directly to the field–neither gives you the opportunity to raise the necessary events (the binding will work, but the value won’t be updated when changed).
Another shortcoming of DataBinding is that it doesn’t consider threading. If a background thread modifies a databound value then the databinding will try to make a cross-threaded call to update the UI–which is bad. The best workaround I’ve found is to let bindable classes hold an instance of their UI’s
Synchronization Context, which will let you ensure updates to the UI are invoked on the UI thread.I know it all sounds discouraging–these shortcomings of databinding were learned the hard way. However, it’s better to be aware of–and compensate for–these issues early on before they manifest as bigger problems.