Search code examples
c#wpfvalidationinotifypropertychangedidataerrorinfo

Validating custom data types with IDataErrorInfo and INotifyPropertyChanged


I have a model for an object holding data, which is bound to an input form. This model uses IDataErrorInfo and INotifyPropertyChanged to validate its contents. I have a method for converting a string like "(6*20+sin(20))" into a double value. The text box for entering this text is bound to Mass.TextValue. However when this value changes, it does not call the OnPropertyChanged() method as seen below, and so the value is not validated, how can I get around this issue?

    private DynamicDouble mass = new DynamicDouble("Mass", 1);
    public DynamicDouble Mass
    {
        get { return mass; }
        set { mass = value; OnPropertyChanged("Mass");  }
    }

The DynamicDouble class also uses INotifyPropertyChanged and IDataErrorInfo as well and the validation inside is called but it is the validation for converting the string into a double value, not for checking whether that value is greater than 0 (in case of the mass). I cannot put that range check in the DynamicDouble class as it is used for more than just the Mass property.


Solution

  • The problem was solved by putting all of the required validation logic into the ViewModel class and adding properties to it that pointed to values in the model itself and validating that input instead of doing the validation lower down.