views:

22

answers:

1

I want to call a generic handler function for all textBox on GotFocus and LostFocus.

For GotFocus I could create:

private void GotFocus()
{
    TextBox textBox = ((TextBox)FocusManager.GetFocusedElement());
    textBox.Text = "";
}

and call it like this:

private void textBox1_GotFocus(object sender, RoutedEventArgs e)
{
    //Instead of this in every TextBox
    //TextBox textBox = (TextBox)sender;
    //textBox.Text = "";
    GotFocus();

}

But for LostFocus I can't do the same to get some symetry handler ? Am I obliged to manage the memorization of the control in GotFocus in a private member so as to be able to use it later in LostFocus ?

Aren't there any way to do this more globally by hooking the .NET system and create this missing GetPreviousFocusedElement function ?

I like the Law of Symetry, that's how Physicians discover new laws and I think this principle could also apply in IT.

+1  A: 

The parameter object sender contains a reference to the control.

private void textBox1_GotFocus(object sender, RoutedEventArgs e)
{
    (sender as TextBox).Text = "";
}

private void textBox1_LostFocus(object sender, RoutedEventArgs e)
{
    (sender as TextBox).Text = "";
}

or whatever you want the LostFocus method to do.

samjudson
I don't want to pass sender, that's the very point :)
All events have a sender parameter - therefore you can write one event handler to handle both the GotFocus and LostFocus events - then use the sender parameter to determine the object that fired the event. If you don't want to use the sender parameter then what you are asking for is probably not possible. You wanted a solution, so I gave you one.
samjudson
ok the problem is rather rooted in .NET which does explicitely use sender as parameter instead of being able to get it whatever the context.