WPF Toggle Button Checked/Uchecked event with one handler

后端 未结 3 926
逝去的感伤
逝去的感伤 2021-02-18 21:27

I am using a ToggleButton in a WPF window:

 

        
相关标签:
3条回答
  • 2021-02-18 22:19

    You can attach a single click event of your ToggleButton and in its handler you can check the ToggleButton IsChecked property by type casting the sender object in your handler like this -

    private void ToggleButton_Click(object sender, RoutedEventArgs e)
    {
       if((sender as ToggleButton).IsChecked)
       {
          // Code for Checked state
       }
       else
       {
          // Code for Un-Checked state
       }
    }
    

    Xaml:

    <ToggleButton Height="37" HorizontalAlignment="Left" Margin="485.738,254.419,0,0"     VerticalAlignment="Top" Width="109" IsEnabled="True" Click="ToggleButton_Click">Timeout</ToggleButton>
    
    0 讨论(0)
  • 2021-02-18 22:29

    Try this

    private void tBtn_super_Click(object sender, RoutedEventArgs e)
            {
                if (tBtn_super.IsChecked == true)
                {
                    MessageBox.Show("True");
                }
                else
                {
                    MessageBox.Show("False");
                }
            }
    
    0 讨论(0)
  • 2021-02-18 22:33

    You should not use Click event as some answers suggest, because it will not work when the property IsChecked is changed by code or any other event than mouse (keyboard, animation..). This is simply a bug.

    Instead you can use the same handler for both Checked and Unchecked and do action depending on IsChecked property.

    <ToggleButton
        Checked="toggleButton_IsCheckedChanged"
        Unchecked="toggleButton_IsCheckedChanged" />
    
    0 讨论(0)
提交回复
热议问题