控制具有相同事件类型的多个文本框
问题描述:
我有一个C#WPF窗口,其中有20个文本框。他们没有做任何特别的事情,我想要的只是当我去选择文本的时候。控制具有相同事件类型的多个文本框
我知道这是相当各设置20个事件,如
private void customerTextBox_GotFocus(object sender, RoutedEventArgs e)
{
customerTextBox.SelectAll();
}
,但我不知道是否有件事更顺畅像
private void (genericTextBox)_GotFocus(object sender, RoutedEventArgs e)
{
(genericTextBox).SelectAll();
}
我可以只使用这个曾经在那里每个文本理解用户该事件
答
创建您的事件处理程序,如您在您的示例中所做的,然后将所有文本框的GotFocus事件指向该处理程序。
答
您可以使用sender
参数,该参数包含引用引发事件的文本框:
private void GenericTextBox_GotFocus(object sender, RoutedEventArgs e)
{
(sender as TextBox).SelectAll();
}
然后,您可以设置此错误处理程序为所有的文本框:
<TextBox x:Name="textBox1" GotFocus="GenericTextBox_GotFocus" />
<TextBox x:Name="textBox2" GotFocus="GenericTextBox_GotFocus" />
<TextBox x:Name="textBox3" GotFocus="GenericTextBox_GotFocus" />
<TextBox x:Name="textBox4" GotFocus="GenericTextBox_GotFocus" />
答
您可以使用“发件人”参数为多个文本框编写一个处理程序。
例子:
private void textBox_GotFocus(object sender, RoutedEventArgs e)
{
TextBox textBox = sender as TextBox;
if (sender == null)
{
return;
}
textBox.SelectAll();
}
答
可以使用RegisterClassHandler方法是这样的:
EventManager.RegisterClassHandler(typeof(YourClass), TextBox.GotFocusEvent, new RoutedEventHandler((s, e) =>
{(s as TextBox).SelectAll();};
答
除了创建通用处理器如前所述,你也可以添加一行代码到你的窗口的构造函数,所以你不必将xaml中的处理程序附加到每个文本框。
this.AddHandler(TextBox.GotFocusEvent, new RoutedEventHandler(TextBox_GotFocus));
完美,谢谢(Damir Arh) – nikolifish 2012-04-09 14:52:02