我的问题是我们如何编写c#代码替换xaml进行绑定验证? 例如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>
如果在c#代码中
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);
////////////////////////////
用户定义验证类
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 < _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;
}
}
////////////////////////////////
但我们如何在c#中编写验证规则以使文本框使用绑定验证?
答案 0 :(得分:2)
只需添加新规则吗?
bindtext.ValidationRules.Add(new NumberRangeRule() { Min = 0, Max = 128 });