关于WPF/Silverlight的数据验证,想必大家都不陌生了。
各大牛的博客里都不泛对这方面讨论的文章。
个人比较赞赏 JV9的“Silverlight实例教程”里的Validation数据验证。
本文是在大牛基础上做了个升级,其验证更加简单和方便。
1、创建验证的基类
public class ValidationBase:IDataErrorInfo,INotifyPropertyChanged { protected string errMsg; private bool hasValidate = false; public string Error { get { if (!hasValidate) { this.Validate(); } return errMsg; } } public string this[string columnName] { get { this.hasValidate = true; List<ValidationResult> resultList = new List<ValidationResult>(); ValidationContext context = new ValidationContext(this, null, null) { MemberName = columnName }; if (Validator.TryValidateProperty(this.GetPropertyValue(columnName), context, resultList)) { return null; } this.errMsg = null; foreach (var item in resultList) { this.errMsg += item.ErrorMessage + Environment.NewLine; } return this.errMsg; } } private object GetPropertyValue(string propName) { PropertyInfo property = base.GetType().GetProperty(propName, BindingFlags.GetProperty | BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly); if (property == null) { return null; } if (property.GetIndexParameters().Length > 0) { return null; } return property.GetValue(this, null); } public virtual bool Validate() { this.hasValidate = true; List<ValidationResult> resultList = new List<ValidationResult>(); bool flag = Validator.TryValidateObject(this, new ValidationContext(this, null, null), resultList, true); this.errMsg = null; foreach (var item in resultList) { this.errMsg += item.ErrorMessage + Environment.NewLine; } return flag; } public event PropertyChangedEventHandler PropertyChanged; public void OnPeropertyChanged(string propName) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(propName)); } } }
继承IDataErrorInfo,提供界面绑定时验证信息的提示,INotifyPropertyChanged做一个扩展,方便实现属性的变更通知机制。
2、所有Model实体继承ValidationBase,例如:
public class Person : ValidationBase { [Required(ErrorMessage="姓名不能为空。")] public string Name { get; set; } [Required(ErrorMessage="年龄不能为空。")] [RegularExpression(@"^\d.$",ErrorMessage="年龄必须为整数。")] public int? Age { get; set; } }
3、页面绑定
Text="{Binding Name, Mode=TwoWay, ValidatesOnDataErrors=True, ValidatesOnExceptions=True}"
如果你喜欢此文,请推荐一下。
最后,转载请注明出处:http://www.cnblogs.com/lisweden/p/4745816.html
时间: 2024-11-09 17:28:28