简体   繁体   中英

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:

<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:

res.IsInheriting = tbIsInheriting.IsChecked;

but this is a mistake (cannot convert source type 'System.Nullable' to target type 'bool').

tblsInheriting.IsChecked.GetValueOrDefault();

CheckBox.IsChecked returns a 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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