2

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

  1. explain why this happens
  2. and how to do it right.

Thank you.

Chibuzo
  • 6,112
  • 3
  • 29
  • 51
  • 2
    +1 good question 1) this happens because the GotFocusEvent is only inherited from UIElement and is passed to .AddHandler resolved as UIElement.GetFocusEvent and therefore applied to all controls that inherit from UIElement – cppanda Jul 02 '12 at 21:54
  • @cppanda Thank you very much for the explanation. Any suggestion on how to add the handler to textboxes alone? – Chibuzo Jul 02 '12 at 22:17

1 Answers1

1

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
    }
Nogusta
  • 909
  • 5
  • 10