WPF Toggle Button Checked/Uchecked event with one handler

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-05 10:27:47

问题


I am using a ToggleButton in a WPF window:

 <ToggleButton Height="37"
          HorizontalAlignment="Left"
          Margin="485.738,254.419,0,0"
          VerticalAlignment="Top"
          Width="109"
          IsEnabled="True"
          Checked="toggleAPDTimeoutErr_Checked"
          Unchecked="toggleAPDTimeoutErr_Unchecked">Timeout</ToggleButton>

I have two events that I am monitoring, but this is done in two different code behind handlers. How can this be done in only one?

I will have many ToggleButtons, and the code can get large.


回答1:


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>



回答2:


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" />



回答3:


Try this

private void tBtn_super_Click(object sender, RoutedEventArgs e)
        {
            if (tBtn_super.IsChecked == true)
            {
                MessageBox.Show("True");
            }
            else
            {
                MessageBox.Show("False");
            }
        }


来源:https://stackoverflow.com/questions/7677906/wpf-toggle-button-checked-uchecked-event-with-one-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!