C# WPF MVVM data validation

945 views Asked by At

I have following WPF-MVVM setup:

  • A view with 2 textfields bound to the properties of the ViewModel with UpdateSourceTrigger=PropertyChanged and a button with a command binding to a relay command (CanExecute, Execute methods)
  • ViewModel which implements INotifyDataErrorInfo with 2 properties annotated with [System.ComponentModel.DataAnnotations.Required]. Property setter call private ViladateProperty method, which stores the validation results in the errors dictionary. HasErrors property getter checks the errors dictionary to return the appropriate value.

The aim is to enable the button as soon as the whole form validates correctly. My two questions on this are:

  • How to implement the CanExecute method of the button relay command without calling the validation on the whole model for every property change?
  • What is the best way to "delay" the UpdateSourceTrigger to set the according property not on every keystroke but, for example, after one second of "no input"?
1

There are 1 answers

3
Sheridan On

Your CanExecute handler should simply refer to your HasErrors property:

... (canExecute) => !HasErrors; ...

•How to implement the CanExecute method of the button relay command without calling the validation on the whole model for every property change?

Can you tell me how the property system could possibly know if there were any validation errors if it didn't check after every key stroke? Think about it... any key stroke could make the model invalid. Either way, you won't notice any delay as it revalidates the model.

•What is the best way to "delay" the UpdateSourceTrigger to set the according property not on every keystroke but, for example, after one second of "no input"?

If you're using .NET 4.5, you're in luck... Microsoft just added a Delay property to the Binding class. This enables you to set the amount of time, in milliseconds, to wait before updating the binding source after the value on the target changes. For full information, please refer to the BindingBase.Delay Property page on MSDN.