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;
    }
}
3
  • Try preview key down Commented Feb 27, 2017 at 8:07
  • You can simply bind the Text to a numeric type (like double for example) in the View Model. Commented Feb 27, 2017 at 8: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. Commented Jul 17, 2019 at 19:16

1 Answer 1

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]+");
}
Sign up to request clarification or add additional context in comments.

3 Comments

This is a copied answer from stackoverflow.com/questions/1268552/…
This approach doesn't handle space keys.
Where is your exclamation point?