【问题标题】:IDataErrorInfo with complex types具有复杂类型的 IDataErrorInfo
【发布时间】:2009-09-17 19:06:46
【问题描述】:

我有一个地址对象,简单定义如下:

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

相当简单。根据我对另一个question 的回答的建议,我指的是this 博客文章,将我的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);

一切都无济于事。

我有什么遗漏吗?

【问题讨论】:

    标签: c# winforms validation data-binding idataerrorinfo


    【解决方案1】:

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

    【讨论】:

    • 致布赖恩。我觉得你不太对。有时对象具有不同的行为和限制,具体取决于父对象的上下文。所以,想象一下,如果我们有一个对象 Sum ,其属性是 Amount 和 Currency。现在我们有了具有金额和货币的汇款类。因此,假设我们有几种类型的汇款,并且在某种类型中,金额受到其性质的限制。那么 Sum 类型的字段如何知道它的数量在某些情况下应该是有限的,而在其他情况下不是?
    【解决方案2】:

    看看my answer here

    这解释了如何使用模型绑定器来添加模型的“类级别”检查,而不必使用IDataError - 正如您在此处看到的那样,这可能非常笨拙。它仍然允许您使用 [Required] 属性或您拥有的任何其他自定义验证属性,但允许您添加或删除单个模型错误。有关如何使用数据注释的更多信息,我强烈推荐this post from Scott Gu

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多