Reputation: 512
I have a C# WPF Window in which I have 20 textboxes. They don't do anything special, and all i want is when I went them for the text to be selected.
I know it's fairly each to set up 20 events like
private void customerTextBox_GotFocus(object sender, RoutedEventArgs e)
{
customerTextBox.SelectAll();
}
but i'm wondering if theres something smoother like
private void (genericTextBox)_GotFocus(object sender, RoutedEventArgs e)
{
(genericTextBox).SelectAll();
}
where I can just use this once and each textbox understands to user that event
Upvotes: 0
Views: 2592
Reputation: 509
In addition to creating the generic handler as aforementioned, you can also add a line of code to your window's constructor so you do not have to attach the handler in xaml to each textbox.
this.AddHandler(TextBox.GotFocusEvent, new RoutedEventHandler(TextBox_GotFocus));
Upvotes: 0
Reputation: 206
you can use RegisterClassHandler method like this:
EventManager.RegisterClassHandler(typeof(YourClass), TextBox.GotFocusEvent, new RoutedEventHandler((s, e) =>
{(s as TextBox).SelectAll();};
Upvotes: 0
Reputation: 2256
You can use the "sender" parameter to write one handler for multiple TextBoxes.
Example:
private void textBox_GotFocus(object sender, RoutedEventArgs e)
{
TextBox textBox = sender as TextBox;
if (sender == null)
{
return;
}
textBox.SelectAll();
}
Upvotes: 2
Reputation: 17855
You can use sender
argument which contains the reference to the textbox that raised the event:
private void GenericTextBox_GotFocus(object sender, RoutedEventArgs e)
{
(sender as TextBox).SelectAll();
}
You can then set this error handler for all your textboxes:
<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" />
Upvotes: 2
Reputation: 10877
Create your event handler as you did in your example and then point all your textbox's GotFocus event to that handler.
Upvotes: 0