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
WPF Toggle Button Checked/Uchecked event with one handler
提问by Ryan R
I am using a ToggleButton
in 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 ToggleButton
s, and the code can get large.
我会有很多ToggleButton
s,代码会变大。
回答by Rohit Vats
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 -
您可以附加您的单击事件,ToggleButton
并在其处理程序中,您可以ToggleButton
IsChecked
通过在处理程序中键入发送者对象来检查属性,如下所示 -
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 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.
您不应该Click
像某些答案所建议的那样使用事件,因为当属性IsChecked
被代码或鼠标以外的任何其他事件(键盘、动画......)更改时,它不起作用。这只是一个错误。
Instead you can use the same handler for both Checked
and Unchecked
and do action depending on IsChecked
property.
相反,您可以根据属性对Checked
andUnchecked
和 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");
}
}