-1

Is it possible to implement an TextBox/NumberBox that filters and only accepts numeric values in real time just like what a NumberBox normaly does but not just when the user completes the input and if so how can I do it?

Clemens
  • 123,504
  • 12
  • 155
  • 268
David Simões
  • 303
  • 4
  • 11

1 Answers1

1

The general approach would be to handle the BeforeTextChanging event:

private void TextBox_BeforeTextChanging(TextBox sender, TextBoxBeforeTextChangingEventArgs e)
{
    if (!string.IsNullOrEmpty(e.NewText))
        foreach (char c in e.NewText)
            if (!char.IsDigit(c))
            {
                e.Cancel = true;
                return;
            }
}

XAML:

<TextBox BeforeTextChanging="TextBox_BeforeTextChanging" />
mm8
  • 163,881
  • 10
  • 57
  • 88