My question is how can we write c# code replace the xaml for binding validation? for example the xaml
<TextBox.Text>
<Binding Path="Age" UpdateSourceTrigger="PropertyChanged">
<!--<Binding Path="Age" NotifyOnValidationError="True">-->
<Binding.ValidationRules>
<!--<ExceptionValidationRule />-->
**<local:NumberRangeRule Min="0" Max="128" />**
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
if in the c# 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);
////////////////////////////
the user define validation class
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 ValidationResul开发者_JS百科t 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 < _min || number > _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;
}
}
////////////////////////////////
but how can we write the validation rules in c# to make the textbox use the binding validation?
Just add a new rule?
bindtext.ValidationRules.Add(new NumberRangeRule() { Min = 0, Max = 128 });
精彩评论