jermny
jermny

Reputation: 880

How do I deal with WPF Validation and MVVM?

I have a WPF page (as my View) in an MVVM model. The View is an entry form with many textboxes. I have a custom ValidationRule built to validate each textbox and display tooltip warnings accordingly. However, I only want the "Commit" button to be enabled when all the validators pass. Right now, my "Commit" button's IsEnabled is bound to the DataContext based on other criteria. How do I add the caveat of "only be enabled when all validators pass" when my IsEnabled is already bound like so?

IsEnabled="{Binding IsDataLoaded}"

Upvotes: 1

Views: 471

Answers (3)

Rachel
Rachel

Reputation: 132558

Your Commit button should be bound to a RelayCommand in your ViewModel, and just set the CanExecute() to only be true if this.IsDataLoaded and this.IsValid

CommitCommand = new RelayCommand(
    param => SaveChanges()
    param => this.IsDataLoaded && this.IsValid
);

For verifying if the ViewModel is valid or not, I would suggest using IDataErrorInfo

Upvotes: 4

Emond
Emond

Reputation: 50672

Assuming that you bind the Button to a Command, make the Command implement CanExecute so it only returns true when the validations rules validate.

Upvotes: 5

Arsen Mkrtchyan
Arsen Mkrtchyan

Reputation: 50712

You can use MultiBinding with converter you want

Upvotes: 0

Related Questions