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

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

    If you do not want to write a lot of code to do a basic function (I don't know why people make long methods) you can just do this:

    1. Add namespace:

      using System.Text.RegularExpressions;
      
    2. In XAML, set a TextChanged property:

      
      
    3. In WPF under txt1_TextChanged method, add Regex.Replace:

      private void txt1_TextChanged(object sender, TextChangedEventArgs e)
      {
          txt1.Text = Regex.Replace(txt1.Text, "[^0-9]+", "");
      }
      

提交回复
热议问题