diff --git a/src/MaterialDesignThemes.Wpf/NumericUpDown.cs b/src/MaterialDesignThemes.Wpf/NumericUpDown.cs index d0f6f33f47..cd6803ba51 100644 --- a/src/MaterialDesignThemes.Wpf/NumericUpDown.cs +++ b/src/MaterialDesignThemes.Wpf/NumericUpDown.cs @@ -1,5 +1,6 @@ using System.ComponentModel; using System.Globalization; +using System.Windows.Automation; namespace MaterialDesignThemes.Wpf; @@ -19,7 +20,42 @@ public class NumericUpDown : Control static NumericUpDown() { DefaultStyleKeyProperty.OverrideMetadata(typeof(NumericUpDown), new FrameworkPropertyMetadata(typeof(NumericUpDown))); - EventManager.RegisterClassHandler(typeof(NumericUpDown), UIElement.GotFocusEvent, new RoutedEventHandler(OnGotFocus)); + + EventManager.RegisterClassHandler(typeof(NumericUpDown), GotFocusEvent, new RoutedEventHandler(OnGotFocus)); + } + + + // Based on work in MahApps + // https://github.com/MahApps/MahApps.Metro/blob/f7ba30586e9670f07c2f7b6553d129a9e32fc673/src/MahApps.Metro/Controls/NumericUpDown.cs#L966 + private static void OnGotFocus(object sender, RoutedEventArgs e) + { + // When NumericUpDown gets logical focus, select the text inside us. + // If we're an editable NumericUpDown, forward focus to the TextBox element + if (!e.Handled) + { + var numericUpDown = (NumericUpDown)sender; + if (numericUpDown.Focusable && e.OriginalSource == numericUpDown) + { + // MoveFocus takes a TraversalRequest as its argument. + var focusDirection = Keyboard.Modifiers.HasFlag(ModifierKeys.Shift) + ? FocusNavigationDirection.Previous + : FocusNavigationDirection.Next; + + var request = new TraversalRequest(focusDirection); + // Gets the element with keyboard focus. + // And change the keyboard focus. + if (Keyboard.FocusedElement is UIElement elementWithFocus) + { + elementWithFocus.MoveFocus(request); + } + else + { + numericUpDown.Focus(); + } + + e.Handled = true; + } + } } #region DependencyProperties @@ -238,12 +274,6 @@ protected override void OnPreviewKeyDown(KeyEventArgs e) OnDecrease(); e.Handled = true; } - // Move to previous element if Shift + Tab is pressed - else if (e.Key == Key.Tab && (Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift) - { - MoveFocus(new TraversalRequest(FocusNavigationDirection.Previous)); - e.Handled = true; - } base.OnPreviewKeyDown(e); } @@ -264,15 +294,5 @@ protected override void OnPreviewMouseWheel(MouseWheelEventArgs e) base.OnPreviewMouseWheel(e); } - private static void OnGotFocus(object sender, RoutedEventArgs e) - { - // When NumericUpDown gets focus move it to the TextBox - NumericUpDown numericUpDown = (NumericUpDown)sender; - if ((!e.Handled) && (numericUpDown._textBoxField != null)) - { - numericUpDown._textBoxField.Focus(); - numericUpDown._textBoxField.SelectAll(); - e.Handled = true; - } - } + public void SelectAll() => _textBoxField?.SelectAll(); }