Freigeben über


How to: Handle the Checked Event for the CheckBox Control

Microsoft Silverlight will reach end of support after October 2021. Learn more.

When a user clicks a CheckBox control, one of three events can occur, depending on the current state of the CheckBox. Either the Checked, Unchecked or Indeterminate event occurs. You can handle these events and perform some action depending on the state of the check box.

Example

The following code demonstrates how to handle the Checked and Indeterminate events.

Private Sub HandleCheck(ByVal sender As Object, ByVal e As RoutedEventArgs)
     Dim cb As CheckBox = CType(sender, CheckBox)
     If (cb.Name = "cb1") Then
         text1.Text = "Two state CheckBox checked."
     Else
         text2.Text = "Three state CheckBox checked."
     End If
 End Sub

 Private Sub HandleUnchecked(ByVal sender As Object, ByVal e As RoutedEventArgs)
     Dim cb As CheckBox = CType(sender, CheckBox)
     If (cb.Name = "cb1") Then
         text1.Text = "Two state CheckBox unchecked."
     Else
         text2.Text = "Three state CheckBox unchecked."
     End If
 End Sub

 Private Sub HandleThirdState(ByVal sender As Object, ByVal e As RoutedEventArgs)
     Dim cb As CheckBox = CType(sender, CheckBox)
     text2.Text = "Three state CheckBox indeterminate."
 End Sub
private void HandleCheck(object sender, RoutedEventArgs e)
{
    CheckBox cb = sender as CheckBox;
    if (cb.Name == "cb1")
        text1.Text = "Two state CheckBox checked.";
    else
        text2.Text = "Three state CheckBox checked.";
}

private void HandleUnchecked(object sender, RoutedEventArgs e)
{
    CheckBox cb = sender as CheckBox;
    if (cb.Name == "cb1")
        text1.Text = "Two state CheckBox unchecked.";
    else
        text2.Text = "Three state CheckBox unchecked.";
}

private void HandleThirdState(object sender, RoutedEventArgs e)
{
    CheckBox cb = sender as CheckBox;
    text2.Text = "Three state CheckBox indeterminate.";
}
<!-- two state CheckBox -->
<CheckBox x:Name="cb1" Content="Two State CheckBox" 
          Checked="HandleCheck" Unchecked="HandleUnchecked" Margin="5" />
<TextBlock x:Name="text1" Margin="5" />

<!-- three state CheckBox -->
<CheckBox x:Name="cb2" Content="Three State CheckBox" 
    IsThreeState="True" Checked="HandleCheck" 
    Indeterminate="HandleThirdState" Unchecked="HandleUnchecked" Margin="5" />
<TextBlock x:Name="text2" Margin="5" />

See Also

Reference