#854 – Clicked vs. Checked/Unchecked Events for CheckBox

If you want to add an event handler for a CheckBox that gets executed whenever a user clicks on the CheckBox, you can take one of two different approaches:

  • Add a handler for the Click event and then check the IsChecked property to discover the new state (checked / unchecked / indeterminate)
  • Handle one or more of the specific events for the individual states–Checked, Unchecked or Indeterminate

When a user clicks on the CheckBox, the specific event (e.g. Checked) is fired, followed by the Click event.

        private void CheckBox_Click(object sender, RoutedEventArgs e)
        {
            CheckBox cb = sender as CheckBox;
            string checkState;

            if (!cb.IsChecked.HasValue)
                checkState = "Indeterminate";
            else
            {
                if (cb.IsChecked == true)
                    checkState = "Checked";
                else
                    checkState = "Unchecked";
            }

            Trace.WriteLine(string.Format("Click event: {0}", checkState));
        }

        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {
            Trace.WriteLine("Checked event");
        }

        private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            Trace.WriteLine("Unchecked event");
        }

        private void CheckBox_Indeterminate(object sender, RoutedEventArgs e)
        {
            Trace.WriteLine("Indeterminate event");
        }

854-001

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #854 – Clicked vs. Checked/Unchecked Events for CheckBox

  1. Pingback: Dew Drop – July 2, 2013 (#1,577) | Alvin Ashcraft's Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: