Question

I have two properties [Say Size, StrVal] in my viewmodel class. One of the constraint is that StrVal length should be less than or equal to Size; This constraint is applied in IDataErrorInfo indexer.

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;
        }
    }

Now consider the following situation

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

But visually still error situation is displayed until I programmatically fire propertyChanged event for "StrVal" property. For that reason I have to use the following code.

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

Please advice whether this is the ideal way to handle the problem. Regards, Anirban

Was it helpful?

Solution

Yes, this is the way IDataErrorInfo works, it will only query for a validation error when a property change notification happens. So ideally your Size property would look like this:

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

Even though you may not be doing any validation on the size property, you should still (as a matter of "best practice") send the property change notification.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top