2012-04-09 98 views
0

我有一個C#WPF窗口,其中有20個文本框。他們沒有做任何特別的事情,我想要的只是當我去選擇文本的時候。控制具有相同事件類型的多個文本框

我知道這是相當各設置20個事件,如

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

,但我不知道是否有件事更順暢像

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

我可以只使用這個曾經在那裏每個文本理解用戶該事件

回答

0

創建您的事件處理程序,如您在您的示例中所做的,然後將所有文本框的GotFocus事件指向該處理程序。

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" /> 
2

您可以使用「發件人」參數爲多個文本框編寫一個處理程序。
例子:

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

完美,謝謝(Damir Arh) – nikolifish 2012-04-09 14:52:02

0

可以使用RegisterClassHandler方法是這樣的:

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

除了創建通用處理器如前所述,你也可以添加一行代碼到你的窗口的構造函數,所以你不必將xaml中的處理程序附加到每個文本框。

this.AddHandler(TextBox.GotFocusEvent, new RoutedEventHandler(TextBox_GotFocus)); 
相關問題