Use the numeric keypad decimal key as the numeric separator for all locales as in Excel

If the locale specifies that the numeric separator is something else then "." (e.g. "," in Belgium) then the numeric keypad decimal key can not be used to enter a numeric separator in a WPF input control. However in applications like Excel this works. How can we do this in a WPF input control?

Very simple: we handle the PreviewKeyDown event and emulate the input of a numeric separator for that locale.

private static void TextBox_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Decimal && NumberFormatInfo.CurrentInfo.NumberDecimalSeparator != ".")
        {
            var _this = (sender as TextBox);
            if (_this != null)
            {
                e.Handled = true;
                var eventArgs = new TextCompositionEventArgs(Keyboard.PrimaryDevice, new TextComposition(InputManager.Current,
                Keyboard.FocusedElement, NumberFormatInfo.CurrentInfo.NumberDecimalSeparator))
                {
                    RoutedEvent = ContentElement.TextInputEvent
                }
            InputManager.Current.ProcessInput(eventArgs);
            }
        }
    }

Schrijf je in op onze nieuwsbrief!