'WPF Checkbox check IsChecked
I'm not talking about an event handler for this, but rather a simple If Statement checking if the CheckBox has been checked. So far I have:
if (chkRevLoop.IsChecked == true){}
But that raises the error:
Cannot implicitly convert type 'bool?' to 'bool'. An explicit conversion exists (are you missing a cast?)
Is there a way to do this that I'm missing?
Solution 1:[1]
You have to do this conversion from bool? to bool, to make it work:
if((bool)(chkRevLoop.IsChecked)){}
Since it is already a bool condition you need not to put true false because if it is true then only it will come inside this if condition else not.
so, no need to even put chkRevLoop.IsChecked == true here, you are by default asking ==true by puttin IsChecked
Solution 2:[2]
Multiple answers already but here is another alternative
if (chkRevLoop.IsChecked.GetValueOrDefault()) {}
From MSDN
Solution 3:[3]
A bool? can be true, false or null, while bool can only be true or false. ? makes a type "nullable" and adds null as a possibility when it normally isn't, so you can probably just use
if ((bool)chkRevLoop.IsChecked == true){}
or
if (chkRevLoop.IsChecked == (bool?)true){}
to make it match up and work. The second is probably better, since I don't know what would happen in the cast if IsChecked is null
Solution 4:[4]
Consider checking if the property has a value:
var isChecked = chkRevLoop.IsChecked.HasValue ? chkRevLoop.IsChecked : false;
if (isChecked){}
Solution 5:[5]
One line is enough to check if the radio button is checked or not:
string status = Convert.ToBoolean(RadioButton.IsChecked) ? "Checked" : "Not Checked";
Solution 6:[6]
IsChecked property of CheckBox is Nullable boolean.
public bool? IsChecked { get; set; }
Create a Nullable boolean and equate it will work for you.
Code
bool? NullableBool = chkRevLoop.IsChecked;
if(NullableBool == true) { }
Solution 7:[7]
You should use Nullable object. Because IsChecked property can be assigned to three different value: Null, true and false
Nullable<bool> isChecked = new Nullable<bool>();
isChecked = chkRevLoop.IsChecked;
if (isChecked.HasValue && isChecked.Value)
{
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Salah Akbari |
| Solution 2 | Yoh Deadfall |
| Solution 3 | |
| Solution 4 | |
| Solution 5 | |
| Solution 6 | |
| Solution 7 |
