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

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

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

      
        
          
            
              
            
          
        
    

    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;
        }
    }
    

提交回复
热议问题