WPF validations using IDataErrorInfo

By | December 8, 2016

In my previous article I have discussed about the first two ways out of total four ways by which we can perform WPF validations. In this article I will discuss the validation using IDataErrorInfo.

Become an Expert in Programming and Web Development.View all courses!

Validation using IDataErrorInfo

  • This is present since .NET 1.0
  • It is supported in windows forms, WPF and carries forward to other XAML technologies also.
  • IDataErrorInfo has two members which need to be implemented by the derived class.
  • The members are ErrorProperty and Indexer.
  • The interface is implemented on the Object which we bind to the WPF control.
  • Here the property is first set to the value and then it comes at the Indexer property checking if the set value is perfect.Once we implement the IDataErrorInfo for the data object which we have to bind to, we need to set the ValidatesOnDataError = true in the XAML. I will use the same View model class which I have used in previous demos. The difference here is that I have to implement the IDataError info to the View Model class.

and the XAML code for the text box is as shown below.

In the above xaml I have provided the validation only for the MobileNumber field. The field will be validated whenever the property value is changed in the textbox. This is done using UpdateSourceTrigger=PropertyChanged in the binding. If we remove this property, the MobileNumber value will be validated only on lost focus from the textbox control.

In my next article I will discuss how to handle the validation asynchronously using INotifyDataErrorInfo.