TobyNick
TobyNick

Reputation: 41

Awareness of validation errors in view model

I have a textbox whose Text property is bound to an integer property in the view model. There is an automatic validation by WPF if the text that is entered by the user is an integer. This functionality is good for me so that I don't need to build additional validation.

Now I have a button whose Command property is bound to a command in the same view model and I want to have the CanExecute method of that command return false if there are any validation errors.

Is there a possibility to know in the view model if there are any validation errors?

Upvotes: 2

Views: 961

Answers (1)

Martin
Martin

Reputation: 5623

I would like to propose this:

  • Add a Boolean HasErrors property to your view model.
  • I your property setters: call one (or more) custom validation methods in your viewmodel (then notify the property change)
  • In the validation method(s): Set the HasErrors property to true if there are errors or set it to false if there are no errors.
  • In your CanExecute method: Check the HasErrors property


This steps above are simplied version of implementing the INotifyDataErrorInfo interface (see this article) which was introduced in .NET 4.5.

If you like you can also completely implement this interface as described in the linked article, but I presume that is more than you need in your case.

With INotifyDataErrorInfo you could set and retrieve a list of errors for each of your properties, but this does not seem to be an requirement in your case, that is why I provided a more simple example with just the one flag HasErrors.

Upvotes: 1

Related Questions