RoutedEventHandler not properly added to the specified elements
-
18-06-2021 - |
题
I'm trying to add RoutedEventHandler
to all the TextBoxes
through code, using the following line of code:
this.AddHandler(TextBox.GotFocusEvent, new RoutedEventHandler(textBox_GotFocus));
The code above binds the handler to all the form control on the Window instead of TextBoxes alone. Please can someone
- explain why this happens
- and how to do it right.
Thank you.
解决方案
Probably not exactly what you are after because it will still fire on every UIElement. But, you can do the following to get the "end result" you need.
public void textBox_GotFocus(object sender, RoutedEventArgs e)
{
var textBox = e.Source as TextBox;
if (textBox == null)
return;
//what ever you wanted to do
}
不隶属于 StackOverflow