How to validate child objects by implementing IDataErrorInfo on parent class

前端 未结 1 2048
挽巷
挽巷 2020-12-18 12:26

I am developing a WPF Application using MVVM Architecture. I am an amateur in WPF so bear with me..

I have two model classes. Parent class has an object of another (

相关标签:
1条回答
  • 2020-12-18 13:24

    You can absolutely implement IDataErrorInfo on a base class using Validation Application Block. Here is an article that describes how to. The code basically comes down to this:

    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);
        }
    }
    

    You can use this abstract class add validation behavior to your entities by inheriting from it:

    public partial class Customer : DataErrorInfo
    {
    }
    
    0 讨论(0)
提交回复
热议问题