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

后端 未结 30 2762
悲哀的现实
悲哀的现实 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条回答
  •  没有蜡笔的小新
    2020-11-22 04:20

    The event handler is previewing text input. Here a regular expression matches the text input only if it is not a number, and then it is not made to entry textbox.

    If you want only letters then replace the regular expression as [^a-zA-Z].

    XAML

    
    

    XAML.CS FILE

    using System.Text.RegularExpressions;
    private void NumberValidationTextBox(object sender, TextCompositionEventArgs e)
    {
        Regex regex = new Regex("[^0-9]+");
        e.Handled = regex.IsMatch(e.Text);
    }
    

提交回复
热议问题