Before reading this article, I highly recommend reading my previous part:
I really want to say thanks to the readers of my previous article “WPF Validation – using DataErrorInfo” for their comments and wishes.
As I said earlier, I got time to write another article, Part II “WPF Validation – using INotifyDataErrorInfo”.
It is always better to understand some theory before practicing it.
Let's dive into that.
The implementation of the INotifyDataErrorInfo interface returns the following 3 things:
- HasErrors: bool property.
- GetErrors: IEnumberable type.
- ErrorsChanged: Event.
The following two things are the main difference compared to an IDataErrorInfo interface implementation.
- Checks the validation asynchronously,
- The ability to store and retrieve multiple errors for a single property.
We will see this very detailed in the following part of this article.
XAML part
The Styling part remains the same as what we did for the IDataErrorInfo implementation. The only one thing is to replace ValidatesOnDataErrors with the ValidatesOnNotifyDataErrors property to true.
Step 1
Implement the INotifyDataErrorInfo interface in the Customer class.
Step 2
Define Dictionary<string, List<string>> locally.
- Dictionary<string, List<string>> propErrors = new Dictionary<string, List<string>>();
Here one for property name another one for list of errors for the given property.
Step 3
We should check the HasErrors property, whether it returns true or not. If it returns true, then only the data validation will be highlighted. We should get the error values from propErrors.
- public bool HasErrors
- {
- get
- {
- try
- {
- var propErrorsCount = propErrors.Values.FirstOrDefault(r =>r.Count>0);
- if (propErrorsCount != null)
- return true;
- else
- return false;
- }
- catch { }
- return true;
- }
- }
Step 4We should get the list of defined errors from the Dictionary.
- public System.Collections.IEnumerable GetErrors(string propertyName)
- {
- List<string> errors = new List<string>();
- if (propertyName != null)
- {
- propErrors.TryGetValue (propertyName, out errors);
- return errors;
- }
- else
- return null;
- }
Step 5
In the OnPropertyChanged() method, we call Validate() to get the errors for each property we have in the Customer class.
Some cases will have more validation for one property. Those defined validation strings will be added into
List<string> listErrors; this list is assigned to adictionary.
- propErrors ["Name"] = listErrors;
If listErrors. Count > 0 then raise the ErrorsChanged Event.
A code sample is attached for your easy reference. Anyway if you want to give it a try then just get my previous article code sample from there. You can just try to implement this concept.
That's all guys. I hope you all understand this concept well. I welcome your comments, questions and suggestions if any.
We will see you soon in the next article.