I want to move to the next control when I press the Enter key instead of the Tab key in a WPF MVVM application. How can I achieve this?
I came up with the below code. Note that it doesn't set e.Handled. Also, MoveFocus_Next doesn't return whether the move focus was successful, but rather if the argument is not null. You can add or remove types of controls to handle as required. The code was written for the MainWindow of the application, but handles other windows as well. You can also adapt the code for invocation from App_Startup event.
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
public partial class MainWindow : Window
{
private bool MoveFocus_Next(UIElement uiElement)
{
if (uiElement != null)
{
uiElement.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
return true;
}
return false;
}
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
EventManager.RegisterClassHandler(typeof(Window), Window.PreviewKeyUpEvent, new KeyEventHandler(Window_PreviewKeyUp));
}
private void Window_PreviewKeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
IInputElement inputElement = Keyboard.FocusedElement;
if (inputElement != null)
{
System.Windows.Controls.Primitives.TextBoxBase textBoxBase = inputElement as System.Windows.Controls.Primitives.TextBoxBase;
if (textBoxBase != null)
{
if (!textBoxBase.AcceptsReturn)
MoveFocus_Next(textBoxBase);
return;
}
if (
MoveFocus_Next(inputElement as ComboBox)
||
MoveFocus_Next(inputElement as Button)
||
MoveFocus_Next(inputElement as DatePicker)
||
MoveFocus_Next(inputElement as CheckBox)
||
MoveFocus_Next(inputElement as DataGrid)
||
MoveFocus_Next(inputElement as TabItem)
||
MoveFocus_Next(inputElement as RadioButton)
||
MoveFocus_Next(inputElement as ListBox)
||
MoveFocus_Next(inputElement as ListView)
||
MoveFocus_Next(inputElement as PasswordBox)
||
MoveFocus_Next(inputElement as Window)
||
MoveFocus_Next(inputElement as Page)
||
MoveFocus_Next(inputElement as Frame)
)
return;
}
}
}
}