Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 更好的实践:CheckBox数据绑定与CheckedChanged事件_C#_.net_Winforms_Data Binding - Fatal编程技术网

C# 更好的实践:CheckBox数据绑定与CheckedChanged事件

C# 更好的实践:CheckBox数据绑定与CheckedChanged事件,c#,.net,winforms,data-binding,C#,.net,Winforms,Data Binding,我有一个复选框,当选中/取消选中该复选框时,将切换其他一些控件的Enabled属性。我确实让我的代码看起来像这样: checkBox.CheckedChanged += new EventHandler((o, e) => { control1.Enabled = checkBox.Checked; control2.Enabled = checkBox.Checked; }); 但今天我开始玩数据绑定,发现我可以做到这一点: control1.DataBindings

我有一个
复选框
,当选中/取消选中该复选框时,将切换其他一些控件的
Enabled
属性。我确实让我的代码看起来像这样:

checkBox.CheckedChanged += new EventHandler((o, e) => 
{
    control1.Enabled = checkBox.Checked;
    control2.Enabled = checkBox.Checked;
});
但今天我开始玩
数据绑定
,发现我可以做到这一点:

control1.DataBindings.Add("Enabled", checkBox, "Checked");
control2.DataBindings.Add("Enabled", checkBox, "Checked");
他们的行为似乎是一样的,但我怀疑一个比另一个更受欢迎。或者可能有人有一些意想不到的行为,可能会绊倒我以后


一种方法比另一种好吗?

第一种方法是在编译时检查的,所以我会选择这种方法。我假设如果第二个示例中的“Enabled”属性无效,您将得到一个运行时错误。

您应该注意到还有另一个区别:
使用数据绑定(方法2),如果对象实现INotifyPropertyChanged,并且如果对象.Enabled在UI层之外更改,则checkbox.checked状态将自动更改。

此外,您将无法自动“重构”第二个状态。