应用自定义验证规则的方法和应用自定义转换器的方法类似。该方法定义了一个 ValidationRule 的类,并且为了执行验证重写 Validate 方法。
public class PositivePriceRule : ValidationRule{
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo){
decimal price = 0;
decimal maxPrice = Decimal.MaxValue;
if (decimal.TryParse(value.ToString(), out price)){
if (price >= 0 && price < maxPrice){
return new ValidationResult(true, null);
}
}
return new ValidationResult(false, "UnitCost cannot be negetive");
}
}
再看Product类
public class Product : INotifyPropertyChanged{
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName){
if (PropertyChanged != null){

本文介绍了在WPF中实现自定义验证规则的方法,通过创建ValidationRule子类并重写Validate方法来执行特定验证。当应用自定义规则如PositivePriceRule时,会触发错误处理,包括文本框样式变更、HasError和Error属性设置以及Error事件。为了提供更好的用户体验,可以考虑增强ErrorTemplate以显示更具指导性的错误信息。
最低0.47元/天 解锁文章
1721

被折叠的 条评论
为什么被折叠?



