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

后端 未结 30 2347
悲哀的现实
悲哀的现实 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:09

    This is the only code needed:

    void MyTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        e.Handled = new Regex("[^0-9]+").IsMatch(e.Text);
    }
    

    This only allows numbers to be inputted into the text box.

    To allow a decimal point or minus sign, you can change the regular expression to [^0-9.-]+.

提交回复
热议问题