1

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?

Glen Thomas
  • 10,190
  • 5
  • 33
  • 65
TobyNick
  • 31
  • 3
  • The easiest Make the integer property nullable `int?` then check the HasValue in the can execute – cleftheris Sep 08 '15 at 13:26
  • 1
    http://stackoverflow.com/questions/30025757/inotifydataerrorinfo-and-binding-exceptions/30030623#30030623 – blindmeis Sep 08 '15 at 13:28
  • You'll have to go with ^ or add code and tell us how you're implementing the validation for the integer property. `int?` may not work since your validation may not update your backing property if its invalid. – Kcvin Sep 08 '15 at 13:37
  • http://stackoverflow.com/questions/22827437/binding-validation-haserror-property-in-mvvm – almulo Sep 08 '15 at 13:42

1 Answers1

1

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.

Martin
  • 5,165
  • 1
  • 37
  • 50