我开始通过IDataErrorInfo接口在WPF项目中实现验证. 我的业务对象包含带有验证信息的多个属性.如何获得与该对象关联的所有错误消息的列表.我的想法是,这就是Error属性的作用,但是我无法追踪使用此属性报告多个属性的任何人.
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 list of ALL the error messages associated with the object. My thought is that thats what the Error property is for, but I cannot track down anyone using this for reporting on multiple properties.
谢谢!
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(LastName)) msg = "Need a first name"; break; default: throw new ArgumentException( "Unrecognized property: " + property); } return msg; } } public string Error { get { return null ; } }推荐答案
是的,我知道您可以在哪里使用索引器.我想这不是一个坏方法.不过,我的确专注于'Error'属性.我喜欢在业务对象中包含错误的概念.我想我想做的事本来就不存在,所以我只是在对象上创建了一个错误字典(在属性更改时随时更新),然后让Error返回CarriageReturn分隔的错误列表,如下所示:
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(); } }更多推荐
如何为多个BO属性定义IDataErrorInfo错误属性
发布评论