Search code examples
c#xamlwindows-phone-7checkboxwindows-phone-8

How to Determine Checked State of Checkbox


I have a checkboxes in a page. I am not sure which event I should be using to examine the checked state. I need to determine if the checkbox is either checked or unchecked. What is the proper method for this? I have seen in researching that the Checkbox actually has three states; Checked, Unchecked, and Indeterminate. This is confusing me as it would seem that only two states will occur to the user. From a user's perspective, the Checkbox will either be Checked or Unchecked, but from my perspective, how do I handle this with the three states? Am I understanding this correctly? Also, what event should I use? Other considerations?

Essentially what I am trying to do is ask the user whether they want to show landmarks on the new map control for WP8. If so, I need to save this setting and also I will limit the map's zoom (which I will do in another area). I just need to determine the user's preference from the checkbox control and save his or her settings. What I have is as follows thus far

<CheckBox x:Name="LandmarksEnabledCheckBox" Checked="LandmarksEnabledCheckBox_Checked">
                        <CheckBox.Content>
                            <TextBlock Text="{Binding Path=LocalizedResources.SettingsPage_LandmarksEnabled, Source={StaticResource LocalizedStrings}}"  TextWrapping="Wrap"/>
                        </CheckBox.Content>
                    </CheckBox>

private void LandmarksEnabledCheckBox_Checked(object sender, RoutedEventArgs e)
    {
        //If CheckBox is checked, set `Settings.LandmarksEnabled.Value = true`, otherwise false
        //??
    }

Solution

  • CheckBox has IsChecked property which is a nullable bool, in other words

    bool?
    

    You could just check if the CheckBox has value, and if it has, take it and compare to true or false.

    if (LandmarksEnabledCheckBox.IsChecked.HasValue)
    {
        if (LandmarksEnabledCheckBox.IsChecked.Value == true)
        {
            //checkbox is checked
        }
        else
        {
            //checkbox is not checked
        }
    }