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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With