简体   繁体   中英

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}"

假设您将Button绑定到Command,则使Command实现CanExecute,以便仅在验证规则验证时返回true。

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

您可以将MultiBinding与所需的转换器一起使用

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM