Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing a data-bound Windows Forms checkbox to change property value immediately when clicked

I have an object that implements INotifyPropertyChanged, and a checkbox that is bound to a boolean property of that object. This works, but I've found that when I check or uncheck the checkbox, the bound property of the object is not updated until I click another control, close the form, or otherwise make the checkbox lose focus.

I would like the checkbox to take effect immediately. That is, when I check the box, the property should be immediately set true, and when I uncheck the box, it should be immediately set false.

I have worked around this by adding a handler for the checkbox's CheckedChanged event, but is there a "right way" to do this that I've overlooked?


A similar Stack Overflow question is Databound value of textbox/checkbox is incorrect until textbox/checkbox is validated.

like image 597
Kristopher Johnson Avatar asked Feb 08 '11 15:02

Kristopher Johnson


1 Answers

Set your binding mode to OnPropertyChanged:

this.objectTestBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.objectTestBindingSource.DataSource = typeof(WindowsFormsApplication1.ObjectTest);

this.checkBox1.DataBindings.Add(
  new System.Windows.Forms.Binding(
    "Checked", 
    this.objectTestBindingSource, 
    "SomeValue", 
    true, 
    System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));

public class ObjectTest: System.ComponentModel.INotifyPropertyChanged
{
    public bool SomeValue
    {
        get { return _SomeValue; }
        set { _SomeValue = value; OnPropertyChanged("SomeValue"); }
    }

    private bool _SomeValue;

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string name)
    {
        if (string.IsNullOrEmpty(name)) {
            throw new ArgumentNullException("name");
        }

        if (PropertyChanged != null) {
            PropertyChanged.Invoke(this, new PropertyChangedEventArgs(name));
        }
    }
}

private void Form1_Load(object sender, EventArgs e)
{
    ObjectTest t = new ObjectTest();
    this.objectTestBindingSource.Add(t);
}

This works as soon as I click on the box.

like image 68
Dustin Davis Avatar answered Nov 11 '22 03:11

Dustin Davis