具有复杂类型的IDataErrorInfo
-
10-07-2019 - |
题
我的Address对象定义如下:
public class Address
{
public string StreetNumber { get; set; }
public string StreetAddress { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
}
相当简单。根据建议我回答另一个问题,我指的是这篇博客文章将我的UI数据绑定到Person类型的对象(其中)包含一个Address MailingAddress字段)。
问题是IDataError接口方法没有验证Address类型的任何属性。
public string this[string columnName]
{
get
{
string result = null;
// the following works fine
if(columnName == "FirstName")
{
if (string.IsNullOrEmpty(this.FirstName))
result = "First name cannot be blank.";
}
// the following does not run
// mostly because I don't know what the columnName should be
else if (columnName == "NotSureWhatToPutHere")
{
if (!Util.IsValidPostalCode(this.MailingAddress.PostalCode))
result = "Postal code is not in a know format.";
}
return result;
}
}
所以,显然我不知道columnName将是什么......我已经逐步完成了它,除了任何公共属性(内在类型)之外,它从来都不是。我甚至尝试过运行并打破如下声明:
if (columnName.Contains("Mailing") || columnName.Contains("Postal"))
System.Windows.Forms.MessageBox.Show(columnName);
一切都无济于事。
我有什么遗失的吗?
解决方案
您需要在要为其提供错误消息的所有类上定义IErrorInfo。
其他提示
请参阅我的答案。
这解释了如何使用模型绑定器添加模型的“类级”检查,而不必使用IDataError
- 正如您在此处看到的那样,这可能非常笨拙。它仍然允许您使用[必需]属性或您拥有的任何其他自定义验证属性,但允许您添加或删除单个模型错误。有关如何使用数据注释的更多信息,我强烈建议 Scott Gu的这篇文章。
不隶属于 StackOverflow