简体   繁体   中英

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?

You can use null coalescing operator . This operator returns right-hand operand if the left-hand operand is null. So you can return false when the CheckBox is in indeterminate state (when the value of IsChecked property is set to null):

if (chkRevLoop.IsChecked ?? false)
{

}

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

Multiple answers already but here is another alternative

if (chkRevLoop.IsChecked.GetValueOrDefault()) {}

From MSDN

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

Consider checking if the property has a value:

var isChecked = chkRevLoop.IsChecked.HasValue ? chkRevLoop.IsChecked : false;

if (isChecked == true){}

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)    {    }

一行足以检查单选按钮是否被选中:

string status = Convert.ToBoolean(RadioButton.IsChecked) ? "Checked" : "Not Checked";

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)
{


}

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