How to set Minvalue and Max Value for a testbox in wpf

Answered How to set Minvalue and Max Value for a testbox in wpf

  • Monday, June 14, 2010 10:56 AM
     
     

    hi,

     

    In my application. I need to validate a textbox like

    If the user enter the minvalue specfied in the textbox it should restrict if the entered value is less than that.  Simliarly if there is a maxvalue specified then it should restrict the user enter greater than the max value.

    How do we acheive this?

All Replies

  • Monday, June 14, 2010 11:15 AM
     
     
  • Monday, June 14, 2010 11:17 AM
     
     Answered
  • Monday, June 14, 2010 11:40 AM
     
     Answered Has Code

    For Validation in WPF you can create ValidationRule. And specify the which validation rules you need to execute at the time of binding in Binding.ValidationRules. So for the same you can create RangeValidationRule.

     public class RangeValidationRule : ValidationRule
      {
        public int MinValue { get; set; }
        public int MaxValue { get; set; }
     
        public override ValidationResult Validate(
          object value, System.Globalization.CultureInfo cultureInfo)
        {
          int intValue;
     
          string text = String.Format ("Must be between {0} and {1}",
                         MinValue, MaxValue);
          if (! Int32.TryParse(value.ToString(), out intValue))
            return new ValidationResult(false, "Not an integer");
          if (intValue < MinValue)
            return new ValidationResult(false, "To small. " + text);
          if (intValue > MaxValue)
            return new ValidationResult(false, "To large. " + text);
          return ValidationResult.ValidResult;
        }
      }
     
    Usage :
    
     <Binding.ValidationRules>
             <local:RangeValidationRule MinValue="3" MaxValue="50" />         
     </Binding.ValidationRules>


    Regards
    Nayan Paregi (MCTS)
    Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread.