控制具有相同事件类型的多个文本框

时间:2012-04-09 14:43:17

标签: c# wpf events

我有一个C#WPF窗口,其中有20个文本框。他们没有做任何特别的事情,而我想要的就是当他们选择文本时。

我知道设置20个事件(例如

)是相当的
private void customerTextBox_GotFocus(object sender, RoutedEventArgs e)
{
    customerTextBox.SelectAll();
}

但我想知道是否有更顺畅的事情

private void (genericTextBox)_GotFocus(object sender, RoutedEventArgs e)
{
    (genericTextBox).SelectAll();
}

我只能使用一次,每个文本框都能理解用户该事件

5 个答案:

答案 0 :(得分:2)

您可以使用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" />

答案 1 :(得分:2)

您可以使用&#34;发件人&#34;为多个TextBox编写一个处理程序的参数 例如:

private void textBox_GotFocus(object sender, RoutedEventArgs e)
{
    TextBox textBox = sender as TextBox;
    if (sender == null)
    {
       return;
    }
    textBox.SelectAll();
 }

答案 2 :(得分:0)

像在示例中一样创建事件处理程序,然后将所有文本框的GotFocus事件指向该处理程序。

答案 3 :(得分:0)

你可以像这样使用RegisterClassHandler方法:

 EventManager.RegisterClassHandler(typeof(YourClass), TextBox.GotFocusEvent, new RoutedEventHandler((s, e) =>
        {(s as TextBox).SelectAll();};

答案 4 :(得分:0)

除了如上所述创建通用处理程序之外,您还可以向窗口的构造函数添加一行代码,这样您就不必将xaml中的处理程序附加到每个文本框中。

this.AddHandler(TextBox.GotFocusEvent, new RoutedEventHandler(TextBox_GotFocus));
相关问题