Multiple component events in one method

Asked

Viewed 129 times

5

I have several events of my textbox, the problem is that I have about 30 in my form. I wonder if there is any way for me to improve my code, reduce it by creating only one method to control all these events.

Three sample Textbox events:

    private void textEmpPrefixo_KeyUp(object sender, KeyEventArgs e)
    {
        var elemento = e.OriginalSource as UIElement;

        if (e.Key == Key.Down)
        {
            elemento.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
        }

        if (e.Key == Key.Up)
        {
            elemento.MoveFocus(new TraversalRequest(FocusNavigationDirection.Previous));
        }
    }

    private void textEmpTelefones_KeyUp(object sender, KeyEventArgs e)
    {
        var elemento = e.OriginalSource as UIElement;

        if (e.Key == Key.Down)
        {
            elemento.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
        }

        if (e.Key == Key.Up)
        {
            elemento.MoveFocus(new TraversalRequest(FocusNavigationDirection.Previous));
        }
    }

    private void textEmpObs2_KeyUp(object sender, KeyEventArgs e)
    {
        var elemento = e.OriginalSource as UIElement;

        if (e.Key == Key.Down)
        {
            elemento.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
        }

        if (e.Key == Key.Up)
        {
            elemento.MoveFocus(new TraversalRequest(FocusNavigationDirection.Previous));
        }
    }

I use them to shift focus as they use the arrow either up or down I use c# wpf technology.

Thank you in advance (:

1 answer

2


You can have only one Handler and us TextBox at the event KeyUp call Handler.

private void MudarFoco_keyUp(object sender, KeyEventArgs e)
{
    var elemento = e.OriginalSource as UIElement;

    if(e.Key == Key.Down)
        elemento.MoveFocus(New TraversalRequest(FocusNavigationDirection.Next));

    if(e.Key == Key.Up)
       elemento.MoveFocus(newTraversalRequest(FocusNavigationDirection.Previous));
}

and in the event of TextBox;

KeyUp="MudarFoco_KeyUp";
  • 1

    Thanks friend, it worked. In case I am applying in the MVVM standard, this method would be in the View same ne?

  • If the answer helped you, mark it as a sure thing!

  • @Emerson, stay in the view, in the case at codebehind of the archive .xml.

  • 1

    Thanks. I just can’t make the answer useful because I need 15 of reputation..

  • Just a small note on terminology: the method MudarFoco_keyUp is not an event - is an Event Handler. KeyUp is an event.

  • Okay buddy... Blz ^^

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.