How do I get a TextBox to only accept numeric input in WPF?

后端 未结 30 2304
悲哀的现实
悲哀的现实 2020-11-22 03:40

I\'m looking to accept digits and the decimal point, but no sign.

I\'ve looked at samples using the NumericUpDown control for Windows Forms, and this sample of a Num

30条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 04:13

    For those looking for a quick and very simple implementation for this type of problem using only integers and decimal, in your XAML file, add a PreviewTextInput property to your TextBoxand then in your xaml.cs file use:

    private void Text_PreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        e.Handled = !char.IsDigit(e.Text.Last()) && !e.Text.Last() == '.';
    }
    

    It's kind of redundant to keep checking the entire string every time unless, as others have mentioned, you're doing something with scientific notation (albeit, if you're adding certain characters like 'e', a simple regex adding symbols/characters is really simple and illustrated in other answers). But for simple floating point values, this solution will suffice.

    Written as a one-liner with a lambda expression:

    private void Text_PreviewTextInput(object sender, TextCompositionEventArgs e) => e.Handled = !char.IsDigit(e.Text.Last() && !e.Text.Last() == '.');
    

提交回复
热议问题