[英]how to convert source type 'System.Nullable<bool>' to target type 'bool'
也许这是一个简单的问题,但我找不到答案。 使用XAML我有这个代码:
<CheckBox Grid.Column="2" Grid.Row="3" Height="23" HorizontalAlignment="Left" Name="tbIsInheriting" VerticalAlignment="Top" Width="191" Margin="0,4,0,0" />
所以在.cs
文件中我需要获得这个Checkbox的值:所以我有:
res.IsInheriting = tbIsInheriting.IsChecked;
但这是一个错误(无法将源类型'System.Nullable'转换为目标类型'bool')。
tblsInheriting.IsChecked.GetValueOrDefault();
CheckBox.IsChecked
返回一个bool?
因为它可以是一个三向复选框。 如果您的复选框从不是三向的,我个人会使用:
res.IsInheriting = tblsInheriting.IsChecked.Value;
如果你的复选框在没有你期望的情况下成为三向,并且处于不确定状态,那将抛出异常。
否则,如果它可能是三向的,我会使用:
res.IsInheriting = tblsInheriting.IsChecked ?? defaultValue;
其中defaultValue
可能为true
或false
具体取决于您希望如何翻译“不确定”状态。
if (tbIsInheriting.IsChecked.HasValue == true)
res.IsInheriting = tbIsInheriting.IsChecked.Value;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.