Abdul Saleem
Abdul Saleem

Reputation: 10622

When will the CheckBox.IsChecked.HasValue become false?

I've used many times the following

if (chkBox.IsChecked.HasValue && chkBox.IsChecked.Value)

But why? What is the situation in which the chkBox.IsChecked.HasValue becomes false?

I checked by creating a checkBox and debugging it to see the HasValue.

Checked on constructor, Checked after Checking and Unchecking the Checkbox. But HasValue always found to be true.

Upvotes: 2

Views: 1469

Answers (2)

stuartd
stuartd

Reputation: 73293

Checkboxes can be ThreeState - the value can be checked, unchecked, or indeterminate. If the value is indeterminate, HasValue returns false.

<CheckBox IsThreeState="True" IsChecked="{x:Null}" />

Upvotes: 2

Patrick Hofman
Patrick Hofman

Reputation: 157048

chkBox.IsChecked is a bool?, which means it is a nullable boolean (it can be set to null). The checkbox can have three values: true, false and null.

HasValue will be false in the case that IsChecked is set to null.

So you could bind to the Checked property and set the value to null, like in this code. HasValue will be false:

chkBox.IsChecked = null;

Also, see the documentation on the usage of Nullable<T>.

Nullable<T> is a struct, and in fact it can't be null. It is just a trick in C#. You see it is null, but in fact it is a struct with HasValue set to false.

Upvotes: 7

Related Questions