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

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

    We can do validation on text box changed event. The following implementation prevents keypress input other than numeric and one decimal point.

    private void textBoxNumeric_TextChanged(object sender, TextChangedEventArgs e) 
    {         
          TextBox textBox = sender as TextBox;         
          Int32 selectionStart = textBox.SelectionStart;         
          Int32 selectionLength = textBox.SelectionLength;         
          String newText = String.Empty;         
          int count = 0;         
          foreach (Char c in textBox.Text.ToCharArray())         
          {             
             if (Char.IsDigit(c) || Char.IsControl(c) || (c == '.' && count == 0))             
             {                 
                newText += c;                 
                if (c == '.')                     
                  count += 1;             
             }         
         }         
         textBox.Text = newText;         
         textBox.SelectionStart = selectionStart <= textBox.Text.Length ? selectionStart :        textBox.Text.Length;     
    } 
    

提交回复
热议问题