简体   繁体   中英

Better Practice: CheckBox DataBindings vs CheckedChanged event

I have a CheckBox that, when checked/unchecked will toggle the Enabled property of some other controls. I did have my code looking something like this:

checkBox.CheckedChanged += new EventHandler((o, e) => 
{
    control1.Enabled = checkBox.Checked;
    control2.Enabled = checkBox.Checked;
});

But today I started playing with DataBindings and discovered I could do this:

control1.DataBindings.Add("Enabled", checkBox, "Checked");
control2.DataBindings.Add("Enabled", checkBox, "Checked");

They seem to behave the same, but I suspect one is preferred over the other. Or perhaps one has some unexpected behavior that may trip me up later.

Is one way better than the other?

The first one is checked at compiled time, so I'd go with that one. I assume that if the "Enabled" property in the second example was not valid you would get a runtime error.

You should notice that there is another difference:
with data binding (method 2), if the object implements INotifyPropertyChanged, and if the object.Enabled is changed outside the UI layer, the checkbox.checked state will get changed automatically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM