How can I define a IDataErrorInfo Error Property for multiple BO properties

后端 未结 3 1649
一个人的身影
一个人的身影 2021-02-06 01:20

I\'m starting to implement validation in my WPF project via the IDataErrorInfo interface. My business object contains multiple properties with validation info. How do I get a l

3条回答
  •  爱一瞬间的悲伤
    2021-02-06 01:59

    Yeah, I see where you could use the indexer. Not a bad way to go I guess. I was really focused on the 'Error' property though. I like the notion of having the errors contained within the business object. I think what I want to do doesnt exist natively, so I just created a dictionary of errors (updated anytime a property changes) on the object and let the Error return a CarriageReturn delimited list of errors, like so :

        public string this[string property]
        {
            get {
    
                string msg = null;
                switch (property)
                {
                    case "LastName":
                        if (string.IsNullOrEmpty(LastName))
                           msg = "Need a last name";
                        break;
                    case "FirstName":
                        if (string.IsNullOrEmpty(FirstName))
                            msg = "Need a first name";
                        break;
                    default:
                        throw new ArgumentException(
                            "Unrecognized property: " + property);
                }
    
                if (msg != null && !errorCollection.ContainsKey(property))
                    errorCollection.Add(property, msg);
                if (msg == null && errorCollection.ContainsKey(property))
                    errorCollection.Remove(property);
    
                return msg;
            }
        }
    
        public string Error
        {
            get
            {
                if(errorCollection.Count == 0)
                    return null;
    
                StringBuilder errorList = new StringBuilder();
                var errorMessages = errorCollection.Values.GetEnumerator();
                while (errorMessages.MoveNext())
                    errorList.AppendLine(errorMessages.Current);
    
                return errorList.ToString();
            }
        }
    

提交回复
热议问题