INotifyDataErrorInfo

Before diving into implementation of INotifyDataErrorInfo, make sure you have a good grasp of WPF Data Binding.

3 important usage/returns of INotifyDataErrorInfo interface:

  1. HasErrors - bool property that is binded when the Model has any error.
  2. GetErrors - IEnumberable
  3. ErrorsChanged - Event

Let’s create a model (Person class) that implements INotifyDataErrorInfo

class Person : INotifyDataErrorInfo
{
       public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;     

       public System.Collections.IEnumerable GetErrors(string propertyName)
       { }

       public bool HasErrors
       {
          get
          {              
            return true;
           }
       }
}

Let’s define a dictionary errors

Dictionary<string, List<string>> errors = new Dictionary<string, List<string>>();

Now, let’s implement HasErrors property

public bool HasErrors
{
    get
    {
        try
        {
            var errorsCount = errors.Values.FirstOrDefault(x => x.Count > 0);
            if (errorsCount != null)
                return true;
            else
                return false;
       }
       catch (Exception ex)
       { 
            throw;
       }
       return true;
    }
 }

Get all errors

public IEnumerable GetErrors(string propertyName)
{
    List<string> errors = new List<string>();
    if (propertyName != null)
    {
        errors.TryGetValue (propertyName, out errors);
        return errors;
    }
    else
        return null;
}

Let’s call Validate() to get the errors for each property we have in the Person class using OnPropertyChanged() method