Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between ValidatesOnNotifyDataErrors and ValidatesOnDataErrors and NotifyOnValidationError in WPF validation?

In WPF validation, whats the difference between the following:

ValidatesOnNotifyDataErrors = True

ValidatesOnDataErrors = True

NotifyOnValidationError = True

When should you use these properties correctly in XAML?

like image 736
kuhajeyan Avatar asked Jun 22 '13 20:06

kuhajeyan


1 Answers

ValidatesOnNotifyDataErrors and ValidatesOnDataErrors are used when you want a XAML bound control to validate its input based on an interface implemented in the ViewModel/Model, for ValidatesOnNotifyDataErrors that interface is INotifyDataErrorInfo and for ValidatesOnDataErrors it is IDataErrorInfo.
for example let's say you have a view model like this:

class PersonViewModel : IDataErrorInfo {      public string FirstName {get; set;}      string IDataErrorInfo.Error      {         return string.Empty;     }      string IDataErrorInfo.this[string columnName] {         if (columnName == "FirstName" &&) {             if (this.FirstName.Length > 20)                 return "FirstName can't be more than 20 characters.";          }         return string.Empty;     }  } 

and then in your view you have a textbox that is bound to the FirstName property like this: <TextBox Text={Binding Path=FirstName, ValidatesOnDataErrors=True} /> now if the user entered 20 characters or more in the textbox an error will be detected.

On the other hand NotifyOnValidationError is used when you want an event to be raised when the bound fails validation.

I usually use ValidatesOnDataErrors in my XAML controls for validation and i haven't had a need for the other two, so it depends on your situation.

EDIT: I am updating my answer as I have learned some new things, so I need to make this more relevant.

ValidatesOnDataErrors is used in thick clients, or in other words when the validation is performed on the client side such as a desktop WPF or WinForm application and model objects implement IDataErrorInfo.

On the other hand, ValidatesOnNotifyDataErrors would be a better fit for thin clients (multi-tier applications) such as client-server applications (Silverlight, WPF with WCF, etc ..) where the validation takes place on the server.

This way when the user types something for example in a TextBox, the value is sent to the server asynchronously for validation, and when validation results come back an event is raised (ErrorsChanged event to be exact), then the view picks that up and displays it using the appropriate method, of course in this case the model would implement INotifyDataErrorInfo.

like image 76
Ibrahim Najjar Avatar answered Sep 28 '22 04:09

Ibrahim Najjar