title: Binding Validation without XAML
body: <p>My question  is how can we write  c#  code replace the xaml for binding validation?
    for example  the xaml </p>
  
  <pre><code>  &lt;TextBox.Text&gt;
          &lt;Binding Path="Age" UpdateSourceTrigger="PropertyChanged"&gt;
            &lt;!--&lt;Binding Path="Age" NotifyOnValidationError="True"&gt;--&gt;
            &lt;Binding.ValidationRules&gt;
              &lt;!--&lt;ExceptionValidationRule /&gt;--&gt;
              **&lt;local:NumberRangeRule Min="0" Max="128" /&gt;**
            &lt;/Binding.ValidationRules&gt;
          &lt;/Binding&gt;
   &lt;/TextBox.Text&gt;  
  </code></pre>
  
  <p>if in the c#  code  </p>
  
  <pre><code>Binding bindtext = new Binding();
  Person person = new Person("Tom",12);
  
  bindtext.Source = person;
  bindtext.Mode = BindingMode.TwoWay;
  bindtext.Path = new PropertyPath("Age");
  
  bindtext.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
  
  bindtext.ValidatesOnExceptions = true;
  
  ageTextBox.SetBinding(TextBox.TextProperty, bindtext);
  </code></pre>
  
  <p>////////////////////////////</p>
  
  <p>the  user define validation class </p>
  
  <pre><code>public class NumberRangeRule : ValidationRule {
      int _min;
      public int Min {
        get { return _min; }
        set { _min = value; }
      }
  
      int _max;
      public int Max {
        get { return _max; }
        set { _max = value; }
      }
  
      public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) {
        int number;
        if( !int.TryParse((string)value, out number) ) {
          return new ValidationResult(false, "Invalid number format");
        }
  
        if( number &lt; _min || number &gt; _max ) {
          string s = string.Format("Number out of range ({0}-{1})", _min, _max);
          return new ValidationResult(false, s);
        }
  
        //return new ValidationResult(true, null);
        return ValidationResult.ValidResult; 
      }
    }
  </code></pre>
  
  <p>////////////////////////////////</p>
  
  <p>but how can we write the validation rules in c#  to make the textbox use the binding validation?</p>