如何通过在父类上实现IDataErrorInfo来validation子对象
我正在使用MVVM架构开发WPF应用程序。 我是WPF的业余爱好者所以请耐心等待..
我有两个模型类。 父类具有另一个(子)类的对象作为其属性。 (我的意思是嵌套对象而不是inheritance对象)
例如,请考虑以下方案。
public class Company { public string CompanyName {get; set;} public Employee EmployeeObj {get; set;} } public class Employee { public string FirstName {get; set;} public string LastName {get; set;} }
我想使用Enterprise Library Validation BlockvalidationEmployee实体的属性。
我可以通过在employee类中实现IDataErroInfo接口来实现,如下所示
public class Employee : IDataErrorInfo { [NotNullValidator(MessageTemplate="First Name is mandatory"] public string FirstName {get; set;} [StringLengthValidator(0,20,MessageTemplate="Invalid")] public string LastName {get; set;} public string Error { get { StringBuilder error = new StringBuilder(); ValidationResults results = Validation.ValidateFromAttributes(this); foreach (ValidationResult result in results) { error.AppendLine(result.Message); } return error.ToString(); } } public string this[string propertyName] { get { ValidationResults results = Validation.ValidateFromAttributes(this); foreach (ValidationResult result in results) { if (result.Key == propertyName) { return result.Message; } } return string.Empty; } } }
我不想为我创建的每个子模型实现IDataErroInfo。
有没有办法通过在父(公司)类上实现IDataErrorInfo来validationEmployee对象?
还有任何触发器来启动对象的validation。 我想只在我想要而不是所有时间validation对象。
您可以使用Validation Application Block在基类上绝对实现IDataErrorInfo
。 这是一篇描述如何的文章 。 代码基本上归结为:
public abstract class DataErrorInfo : IDataErrorInfo { string IDataErrorInfo.Error { get { return string.Empty; } } string IDataErrorInfo.this[string columnName] { get { var prop = this.GetType().GetProperty(columnName); return this.GetErrorInfo(prop); } } private string GetErrorInfo(PropertyInfo prop) { var validator = this.GetPropertyValidator(prop); if (validator != null) { var results = validator.Validate(this); if (!results.IsValid) { return string.Join(" ", results.Select(r => r.Message).ToArray()); } } return string.Empty; } private Validator GetPropertyValidator(PropertyInfo prop) { string ruleset = string.Empty; var source = ValidationSpecificationSource.All; var builder = new ReflectionMemberValueAccessBuilder(); return PropertyValidationFactory.GetPropertyValidator( this.GetType(), prop, ruleset, source, builder); } }
您可以通过inheritance它来使用此抽象类向您的实体添加validation行为:
public partial class Customer : DataErrorInfo { }