2012-04-27 60 views
4

我将信息显示为启用ThreeState的复选框,并希望以最简单的方式使用可为null的布尔值。如何将一个可空的布尔绑定到复选框?

当前我正在使用嵌套的三元表达式;但有没有更清晰的方法?

bool? foo = null; 
checkBox1.CheckState = foo.HasValue ? 
    (foo == true ? CheckState.Checked : CheckState.Unchecked) : 
    CheckState.Indeterminate; 

*请注意,复选框和窗体是只读的。

回答

4

这就是我会这么做的。

我会添加一个扩展方法来清理它。

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; 
    } 
+0

它在所有地方重复,所以我想简化的原因。 – JYelton 2012-04-27 20:18:38

+0

只需为您写入扩展方法代码,1秒 – 2012-04-27 20:19:36

+0

我熟悉扩展方法,但我不确定如何处理“ThreeState”未启用的情况。 – JYelton 2012-04-27 20:20:23

2

更清楚的是一个有争议的说法。例如,我可以说这更清楚。

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 

} 

不过,我喜欢你的代码。

+0

我喜欢'GetCheckState()'方法的想法。 – JYelton 2012-04-27 20:31:44

+0

您也可以扩展该方法并通过复选框。所以你可以测试是否启用了ThreeState。 – Steve 2012-04-27 20:42:56

0

基于扩展方法@弥敦道的建议下,我想出了这个:

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; 

对战设置启用三态-复选框:

checkBox2.SetCheckedNull(someNullableBool); 

后者只是感觉不同足够塔它调整了一点OCD。 :)

相关问题