我将信息显示为启用ThreeState的复选框,并希望以最简单的方式使用可空布尔值。
目前,我使用的是嵌套的三元表达式;但是有更清楚的方法吗?
bool? foo = null;
checkBox1.CheckState = foo.HasValue ?
(foo == true ? CheckState.Checked : CheckState.Unchecked) :
CheckState.Indeterminate;*请注意,复选框和表单是只读的。
发布于 2012-04-27 20:17:46
我就是这么做的。
我会添加一个扩展方法来清理它。
public static CheckState ToCheckboxState(this bool booleanValue)
{
return booleanValue.ToCheckboxState();
}
public static CheckState ToCheckboxState(this bool? booleanValue)
{
return booleanValue.HasValue ?
(booleanValue == true ? CheckState.Checked : CheckState.Unchecked) :
CheckState.Indeterminate;
}发布于 2012-04-27 20:20:25
更清楚的是有争议的陈述。例如,我可以说这一点更清楚。
if(foo.HasValue)
{
if(foo == true)
checkBox1.CheckState = CheckState.Checked;
else
checkBox1.CheckState = CheckState.Unchecked;
}
else
checkBox1.CheckState = CheckState.Indeterminate;另一种选择是为此创建一个方法:
checkBox1.CheckState = GetCheckState(foo);
public CheckState GetCheckState(bool? foo)
{
if(foo.HasValue)
{
if(foo == true)
return CheckState.Checked;
else
return CheckState.Unchecked;
}
else
return CheckState.Indeterminate
}不过,我喜欢你的代码。
发布于 2012-04-27 20:30:48
基于@Nathan关于扩展方法的建议,我得出如下结论:
public static void SetCheckedNull(this CheckBox c, bool? Value)
{
if (!c.ThreeState)
c.Checked = Value == true;
else
c.CheckState = Value.HasValue ?
(Value == true ? CheckState.Checked : CheckState.Unchecked) :
CheckState.Indeterminate;
}我唯一不喜欢的是,当设置“正常”复选框时:
checkBox1.Checked = someBool;与设置启用ThreeState复选框相比:
checkBox2.SetCheckedNull(someNullableBool);后者只是感觉有足够的不同,它稍微调整了强迫症。:)
https://stackoverflow.com/questions/10357266
复制相似问题