简体   繁体   English

如何将源类型'System.Nullable <bool>'转换为目标类型'bool'

[英]how to convert source type 'System.Nullable<bool>' to target type 'bool'

Maybe this is a simple question, but I can't find the answer. 也许这是一个简单的问题,但我找不到答案。 Using XAML I have this code: 使用XAML我有这个代码:

<CheckBox Grid.Column="2"  Grid.Row="3" Height="23" HorizontalAlignment="Left" Name="tbIsInheriting"  VerticalAlignment="Top" Width="191" Margin="0,4,0,0" />

so in .cs file I need to get value of this Checkbox: so I have: 所以在.cs文件中我需要获得这个Checkbox的值:所以我有:

res.IsInheriting = tbIsInheriting.IsChecked;

but this is a mistake (cannot convert source type 'System.Nullable' to target type 'bool'). 但这是一个错误(无法将源类型'System.Nullable'转换为目标类型'bool')。

tblsInheriting.IsChecked.GetValueOrDefault();

CheckBox.IsChecked returns a bool? CheckBox.IsChecked返回一个bool? because it can be a three-way checkbox. 因为它可以是一个三向复选框。 If your checkbox is never three-way, I would personally use: 如果您的复选框从不是三向的,我个人会使用:

res.IsInheriting = tblsInheriting.IsChecked.Value;

That will throw an exception if somehow your check box has become three-way without you expecting it, and is in the indeterminate state. 如果你的复选框在没有你期望的情况下成为三向,并且处于不确定状态,那将抛出异常。

Otherwise, if it might be three-way, I would use: 否则,如果它可能是三向的,我会使用:

res.IsInheriting = tblsInheriting.IsChecked ?? defaultValue;

where defaultValue would probably be true or false depending on how you want the "indeterminate" state to be translated. 其中defaultValue可能为truefalse具体取决于您希望如何翻译“不确定”状态。

if (tbIsInheriting.IsChecked.HasValue == true)
     res.IsInheriting = tbIsInheriting.IsChecked.Value;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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