0

I need to achieve switching from textbox to textbox, button to textbox etc by pressing enter so I am wondering is there some simple way to do this, like it is WIN FORM, change property like priority 1,2,3,4 and as user pressing enter controls will be switched by numbers from lower to higher.

In wpf I couldn't find that solution but I found this, so I am wondering is it OK?!

Here is my code:

private void Grid_PreviewKeyDown_1(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Key == Key.Enter)
                {
                    TextBox s = e.Source as TextBox;
                    if (s != null)
                    {
                        s.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
                    }
                    else
                    {
                        ComboBox cb = e.Source as ComboBox;
                        if (cb != null)
                        {
                            cb.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
                        }
                        else
                        {
                            Button b = e.Source as Button;
                            if (b != null)
                            {
                                b.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
                            }
                        }
                    }

                    e.Handled = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

My controls are contained in Grid.

Thanks guys Cheers!

billy_56
  • 649
  • 3
  • 11
  • 27

1 Answers1

1

Since all child elements of a Grid share the same base class (UIElement) you should be able to simplify the code a bit:

private void Grid_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        UIElement element = e.Source as UIElement;
        element.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
    }
}
mm8
  • 163,881
  • 10
  • 57
  • 88
  • this works but its not switching controls from top to the bottom acctually its jumping random up and down over my controls? – billy_56 Mar 31 '17 at 07:54
  • You can control the order by setting the TabIndex property of the controls: http://stackoverflow.com/questions/359758/setting-tab-order-in-wpf – mm8 Mar 31 '17 at 12:26