Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interpret enter as tab WPF

I want to interpret Enter key as Tab key in whole my WPF application, that is, everywhere in my application when user press Enter I want to focus the next focusable control,except when button is focused. Is there any way to do that in application life circle? Can anyone give me an example?
Thanks a lot!

like image 999
Arsen Mkrtchyan Avatar asked May 16 '09 03:05

Arsen Mkrtchyan


3 Answers

You can use my EnterKeyTraversal attached property code if you like. Add it to the top-level container on a WPF window and everything inside will treat enter as tab:

<StackPanel my:EnterKeyTraversal.IsEnabled="True">
    ...
</StackPanel>
like image 117
Matt Hamilton Avatar answered Nov 03 '22 03:11

Matt Hamilton


Based on Richard Aguirre's answer, which is better than the selected answer for ease of use, imho, you can make this more generic by simply changing the Grid to a UIElement.

To change it in whole project you need to do this

  • In App.xaml.cs:

     protected override void OnStartup(StartupEventArgs e)
     {           
         EventManager.RegisterClassHandler(typeof(UIElement), UIElement.PreviewKeyDownEvent, new KeyEventHandler(Grid_PreviewKeyDown));
         base.OnStartup(e);
     }
    
     private void Grid_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
     {
         var uie = e.OriginalSource as UIElement;
    
         if (e.Key == Key.Enter)
         {
             e.Handled = true;
             uie.MoveFocus(
             new TraversalRequest(
             FocusNavigationDirection.Next));
         }
     }
    
  • Compile. And done it. Now you can use enter like tab. Note: This work for elements in the grid

like image 45
Richard Aguirre Avatar answered Nov 03 '22 04:11

Richard Aguirre


I got around woodyiii's issue by adding a FrameworkElement.Tag (whose value is IgnoreEnterKeyTraversal) to certain elements (buttons, comboboxes, or anything I want to ignore the enter key traversal) in my XAML. I then looked for this tag & value in the attached property. Like so:

    if (e.Key == Key.Enter)
    {
        if (ue.Tag != null && ue.Tag.ToString() == "IgnoreEnterKeyTraversal")
        {
            //ignore
        }
        else
        {
            e.Handled = true;
            ue.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
        }
    }
like image 4
Matt Avatar answered Nov 03 '22 04:11

Matt