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

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

    Add in a VALIDATION RULE so that when the text changes, check to determine if the data is numeric, and if it is, allows processing to continue, and if it is not, prompts the user that only numeric data is accepted in that field.

    Read more in Validation in Windows Presentation Foundation

    0 讨论(0)
  • 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;     
    } 
    
    0 讨论(0)
  • 2020-11-22 04:05

    Could also simply implement a validation rule and apply it to the TextBox:

      <TextBox>
        <TextBox.Text>
          <Binding Path="OnyDigitInput" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">
            <Binding.ValidationRules>
              <conv:OnlyDigitsValidationRule />
            </Binding.ValidationRules>
          </Binding>
        </TextBox.Text>
    

    With the implementation of the rule as follow (using the same Regex as proposed in other answers):

    public class OnlyDigitsValidationRule : ValidationRule
    {
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            var validationResult = new ValidationResult(true, null);
    
            if(value != null)
            {
                if (!string.IsNullOrEmpty(value.ToString()))
                {
                    var regex = new Regex("[^0-9.-]+"); //regex that matches disallowed text
                    var parsingOk = !regex.IsMatch(value.ToString());
                    if (!parsingOk)
                    {
                        validationResult = new ValidationResult(false, "Illegal Characters, Please Enter Numeric Value");
                    }
                }
            }
    
            return validationResult;
        }
    }
    
    0 讨论(0)
  • 2020-11-22 04:06

    Here is a library for numeric input in WPF

    It has properties like NumberStyles and RegexPatternfor validation.

    Subclasses WPF TextBox

    0 讨论(0)
  • 2020-11-22 04:06

    When checking a number value you can use the VisualBasic.IsNumeric function.

    0 讨论(0)
  • 2020-11-22 04:07

    I allowed numeric keypad numbers and backspace:

        private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            int key = (int)e.Key;
    
            e.Handled = !(key >= 34 && key <= 43 || 
                          key >= 74 && key <= 83 || 
                          key == 2);
        }
    
    0 讨论(0)
提交回复
热议问题