0

I use a WPF application I would like to allow only numbers in a textbox. In a WindowsForm application I would know how I would have to make it.
Unfortunately, there is a KeyPress not in WPF and the "code" functioned also no longer.

How is it right and what is the event?


Here you can see the old code that has worked in Windows Form:

private void tbKreisdurchmesser_KeyPress(object sender, KeyEventArgs e)
{
    if (char.IsNumber(e.Key) || e.KeyChar==".")
    {

    }
    else
    {
        e.Handled = e.KeyChar != (char)Keys.Back;
    }
}
Paul Michaels
  • 16,185
  • 43
  • 146
  • 269
  • Try preview key down – paparazzo Feb 27 '17 at 08:07
  • You can simply bind the Text to a numeric type (like `double` for example) in the View Model. –  Feb 27 '17 at 08:12
  • Second on binding to a numeric type, you'll need to specify the property, TwoWay mode, and UpdateSourceTrigger as PropertyChanged, then in your setter, call OnPropertyChanged. This is cool too because it gives you coloring on the text field when the field is invalid. – Trevor Hart Jul 17 '19 at 19:16

1 Answers1

5

You can add Previewtextinput event for textbox and validate the value inside that event using Regex,

private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    var textBox = sender as TextBox;
    e.Handled = Regex.IsMatch(e.Text, "[^0-9]+");
}
mm8
  • 163,881
  • 10
  • 57
  • 88
Prajeesh T S
  • 158
  • 1
  • 9