簡體   English   中英

如何將源類型'System.Nullable <bool>'轉換為目標類型'bool'

[英]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可能為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