Search code examples
c#wpfmvvminotifydataerrorinfo

Mvvm model validation with INotifyDataErrorInfo


my model implements the INotifyDataErrorInfo interface to validate it's properties, and it works fine, but the probleme is, the property HasErrors is by default false, so when i run my app at the first time and click save (form is empty) the view raise no errors, and the data is saved.

here is a snipet of my viewmodel

public LoggingViewModel()
{
    _loggingCommand = new RelayCommand(checkCredentials, canExecuteLogginForm);
    _logingModel = new LoggingModel();

    // I raise this event in the 'OnErrorsChanged' method in the model,
    // so my ViewModel can subscribe and check the 'HasErrors' property.
    _logingModel.FormIsValid += (o, e) => _loggingCommand.RaiseCanExecuteChanged();
}

private bool canExecuteLogginForm()
{
    return !_logingModel.HasErrors;
}

how do you handle this situation in your app?

for more info i created this github repos.


Solution

  • As the LogginModel is actually in an invalid state originally you should call the ValidateForm() method in its constructor to actually set it into this state and populate the _errors dictionary in order for the HasErrors property to return true as it should:

    public class LoggingModel : PocoBase
    {
        public LoggingModel()
        {
            ValidateForm();
        }
    
        [Display(Name = "Name")]
        [MaxLength(32), MinLength(4)]
        public string UserName
        {
            get { return GetValue<string>(); }
            set { SetValue(value); }
        }
    
        [Required]
        public string Password
        {
            get { return GetValue<string>(); }
            set { SetValue(value); }
        }
    }