IDataErrorInfo问题

时间:2013-02-08 16:26:38

标签: c# wpf mvvm idataerrorinfo

我的viewmodel类中有两个属性[Say Size,StrVal]。 其中一个约束是StrVal长度应小于或等于Size; 此约束适用于IDataErrorInfo索引器。

public string this[string propertyName]
    {

       get
       {
            string msg = null; ;
            switch (propertyName)
            {
                ....

                case "StrVal":
                    {
                        if (this.StrVal.Length > this.SizeOfStringVal)
                        {
                            msg = "Size of entered value is greater than the size";
                        }
                    }
                    break;

                .........

            }
            return msg;
        }
    }

现在考虑以下情况

Size = 5;
StrVal = "ABCDEF" ; // length = 6 > Size
"Error message is generated"
Size = 7 // length of StrVal is less than 7

但是在我以编程方式触发“StrVal”属性的propertyChanged事件之前,会显示视觉上仍然出错的情况。出于这个原因,我必须使用以下代码。

public int? Size
    {
        get
        {
            return this.size;
        }
        set
        {
            if (value == this.Size)
            {
                return;
            }
            this.size = value;
            this.OnPropertyChanged("StrVal");
        }
    }

请告知这是否是处理问题的理想方式。 问候, Anirban

1 个答案:

答案 0 :(得分:4)

是的,这是IDataErrorInfo的工作方式,它只会在发生属性更改通知时查询验证错误。理想情况下,您的Size属性看起来像这样:

public int? Size
{
    get
    {
        return this.size;
    }
    set
    {
        if (value == this.Size)
        {
            return;
        }
        this.size = value;
        this.OnPropertyChanged("Size");
        this.OnPropertyChanged("StrVal");
    }
}

即使您可能没有对size属性进行任何验证,您仍然应该(最好的做法")发送属性更改通知。

相关问题