WPF validation and CanExecute command

2k Views Asked by At

I'm trying to get the essence of my last question and bring some more clarity to the description.

Given is an WPF form to submit new data with two textfields and a "Save" button. Both textfields are required fields and are bound to ViewModel properties. Button is bound to "Execute" relay command with Execute and CanExecute methods. CanExecute returns !HasErrors of the ViewModel. ViewModel implements INotifyPropertyChanged and INotifyDataErrorInfo interfaces. Property setter runs the validation for this property only.

The goals are:

  • Disable the "Save" button initially.
  • Enable the "Save" button only if both textfields are validated successfully without validation of the whole ViewModel on every property change.

For the first goal I use the isValidated bool property which is initially false and become true as soon as first validation occurred. This property is then checked together with HasErros in the CanExecute method. Is there a more elegant way?

I have no idea how to implement the second goal. Any thought on this?

THX

1

There are 1 best solutions below

0
On

Your two goals are only one goal really. Let's look at your second goal first:

• Enable the "Save" button only if both textfields are validated successfully without validation of the whole ViewModel on every property change.

Initially, your text fields will be empty, so presumably, they will not pass validation. Therefore initially, your Save Button will be disabled, as per your first goal:

• Disable the "Save" button initially.

Secondly, in your last question (which you should probably add a link to if you're going to mention it in this post), you had some problem with using !HasErros in the CanExecute handler. This time, you do need to validate all of the properties together to fulfil your second requirement... so just use !HasErros in the CanExecute handler.