我有一组
WPF CheckBoxes,它们有一个Checked事件处理程序,当用户点击其中一个时,它处理一些逻辑.但是,我还有一个“全部清除”按钮,单击该按钮将清除所有复选框.如果用户点击“全部清除”按钮,我不希望复选框触发他们的Checked事件.有办法做到这一点吗?
解决方法
在Clear All按钮的事件处理程序的开头删除事件处理程序,然后在Clear All按钮的事件处理程序的末尾重新添加事件处理程序.
这是一个肮脏的样本:
XAML
<Window x:Class="UncheckedTest.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <Grid> <CheckBox Height="16" Margin="22,30,136,0" Name="checkBox1" VerticalAlignment="Top" Unchecked="checkBox1_Unchecked">CheckBox 1</CheckBox> <CheckBox Height="16" Margin="22,76,0" Name="checkBox2" VerticalAlignment="Top" Unchecked="checkBox2_Unchecked">CheckBox 2</CheckBox> <CheckBox Margin="22,121" Name="checkBox3" Height="16" VerticalAlignment="Bottom" Unchecked="checkBox3_Unchecked">CheckBox 3</CheckBox> <Button HorizontalAlignment="Right" Margin="0,118,37,121" Name="button1" Width="87" Click="button1_Click">Uncheck All</Button> <TextBox Height="74" Margin="22,20,13" Name="textBox1" VerticalAlignment="Bottom" TextWrapping="Wrap" VerticalScrollBarVisibility="Visible" /> </Grid> </Window>
代码背后
using System; using System.Windows; namespace UncheckedTest { /// <summary> /// Interaction logic for Window1.xaml /// </summary> public partial class Window1 : Window { private int i = 1; public Window1() { InitializeComponent(); } void checkBox3_Unchecked(object sender,RoutedEventArgs e) { textBox1.Text = i++.ToString() + ". CheckBox 3 Unchecked." + Environment.NewLine + textBox1.Text; } void checkBox2_Unchecked(object sender,RoutedEventArgs e) { textBox1.Text = i++.ToString() + ". CheckBox 2 Unchecked." + Environment.NewLine + textBox1.Text; } void checkBox1_Unchecked(object sender,RoutedEventArgs e) { textBox1.Text = i++.ToString() + ". CheckBox 1 Unchecked." + Environment.NewLine + textBox1.Text; } private void button1_Click(object sender,RoutedEventArgs e) { checkBox1.Unchecked -= checkBox1_Unchecked; checkBox2.Unchecked -= checkBox2_Unchecked; checkBox3.Unchecked -= checkBox3_Unchecked; checkBox1.IsChecked = false; checkBox2.IsChecked = false; checkBox3.IsChecked = false; checkBox1.Unchecked += checkBox1_Unchecked; checkBox2.Unchecked += checkBox2_Unchecked; checkBox3.Unchecked += checkBox3_Unchecked; } } }