2009-09-17 115 views
2

我有简单地定义一个地址对象如下:IDataErrorInfo的复杂类型

public class Address 
{ 
    public string StreetNumber { get; set; } 
    public string StreetAddress { get; set; } 
    public string City { get; set; } 
    public string PostalCode { get; set; } 
} 

相当简单。在建议中,我回答了另一个question问题,我将数据绑定到Person类型的对象(包含Address MailingAddress字段)时指的是this博客文章。

问题是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); 

所有无济于事。

有什么我失踪了吗?

回答

3

您需要在所有要为其提供错误消息的类上定义IErrorInfo。

+0

给Brian。我认为你不太对。有时,对象根据父对象的上下文具有不同的行为和限制。所以,想象一下如果我们有对象总和与财产金额和货币。现在我们有汇款和汇款。所以,假设我们有几种类型的汇款,而某些类型的汇款受其性质限制。那么Sum类型的领域如何知道它的数量在某些情况下应该是有限的,而在其他情况下呢? – 2009-11-13 08:39:10

0

看看my answer here

这解释了如何使用模型绑定器来添加模型级别的检查,而不必使用IDataError--正如你在这里看到的那样可能相当笨拙。它仍允许使用[必需的]属性或任何其他自定义验证属性,但可以添加或删除单个模型错误。有关如何使用数据注释的更多信息,我强烈建议使用this post from Scott Gu