WPF Toggle Button Checked/Uchecked 事件与一个处理程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7677906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 23:06:53  来源:igfitidea点击:

WPF Toggle Button Checked/Uchecked event with one handler

wpfeventstogglebutton

提问by Ryan R

I am using a ToggleButtonin a WPF window:

ToggleButton在 WPF 窗口中使用 a :

 <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.

我会有很多ToggleButtons,代码会变大。

回答by Rohit Vats

You can attach a single click event of your ToggleButtonand in its handler you can check the ToggleButtonIsCheckedproperty by type casting the sender object in your handler like this -

您可以附加您的单击事件,ToggleButton并在其处理程序中,您可以ToggleButtonIsChecked通过在处理程序中键入发送者对象来检查属性,如下所示 -

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

Xaml:

Xml:

<ToggleButton Height="37" HorizontalAlignment="Left" Margin="485.738,254.419,0,0"     VerticalAlignment="Top" Width="109" IsEnabled="True" Click="ToggleButton_Click">Timeout</ToggleButton>

回答by Arek

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

您不应该Click像某些答案所建议的那样使用事件,因为当属性IsChecked被代码或鼠标以外的任何其他事件(键盘、动画......)更改时,它不起作用。这只是一个错误。

Instead you can use the same handler for both Checkedand Uncheckedand do action depending on IsCheckedproperty.

相反,您可以根据属性对CheckedandUnchecked和 do 操作使用相同的处理程序IsChecked

<ToggleButton
    Checked="toggleButton_IsCheckedChanged"
    Unchecked="toggleButton_IsCheckedChanged" />

回答by Raghulan Gowthaman

Try this

尝试这个

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