CheckBox.Checked Data Binding Bug in .NET Compact Framework

Have I mentioned lately how much I like data binding, lately? I use it everywhere I can: it makes writing UI code much easier. Anyway, working on a project at work I ran into the following problem:

Consider this code:

this.checkBox1.DataBindings.Add("Checked", this.myBindingSource, "MyBooleanProperty",
                                 true, DataSourceUpdateMode.OnPropertyChanged);

This declares a data binding on checkBox1, a CheckBox control. It uses the giant overload taking arguments that, respectively, declare the name of the property on the Control to bind to, the source of the data property, the data property, a boolean for formatting, and a DataSourceUpdateMode enum value.

The DataSourceUpdateMode.OnPropertyChanged value means that as soon as the control’s Checked property changes, then change the MyBooleanProperty on the data source. OnPropertyChanged is not the default; the default is OnValidation which typically happens when the control loses focus. I’m a fan of PropertyChanged because there are problems with OnValidation when focus doesn’t change.

Anyway, if you bind to the Checked property on CheckBox, and select DataSourceUpdateMode.OnPropertyChanged, then it updates on validation.

BZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZT! Wrong! Bug!

Fortunately, there is a workaround. If you use the useless, and practically redundant, CheckState property on CheckBox, instead of Checked, then you get OnPropertyChanged updating. Important: Make sure ‘true’ is passed for the formattingEnabled parameter, otherwise the value expected by the control will be of type CheckState, an enum.

The following code works:

this.checkBox1.DataBindings.Add("CheckState", this.myBindingSource, "MyBooleanProperty", 
                                true, DataSourceUpdateMode.OnPropertyChanged);

Your welcome.