How to use model validation rules in WPF ViewModel

I am using WPF with the MVVM template and starting a very large project.

To separate the problems, I want to put all my validation rules in my data models.

But when I look at how to perform WPF validation, all the examples I can find show how to do this with a ViewModel containing validation rules. Some of these examples show some real deep understanding of WPF and are very cool.

In this particular application, I have a 1: 1 mapping between ViewModels, which edits and models, so I can put it in ViewModels. But this is simply not the case.

+7
c # validation wpf mvvm
source share
1 answer

Validation using IDataErrorInfo (if that is what you are using) will happen on the object that is associated with the view.

so if you

 <TextBox Text="{Binding Name}" /> 

it will be in the ViewModel. However, if you expose the model as a property in the presentation model, validation will occur in your data model.

 <TextBox Text="{Binding Model.Name}" /> 

With the first choice, you can bind to the properties of the view model and route to the data model where it contains the actual check, and then just implement IDataErrorInfo in the view model and redirect the check to the model

ViewModel:

 public string this[string propname] { get { return _model[propname]; } } 

This is only useful if you have really set the required model properties to verify operation.

ViewModel:

 public string SomeProperty { get { reutrn _model.SomeProperty; } set { _model.OtherProperty = value; RaisePropertyChanged("SomeProperty"); } } 

However, I prefer the second binding option, because the problem is that it is not very DRY, therefore I almost always expose the DataModel as a property in the view model (since this is responsible for the data) and leave the ViewModel controls the model for the view, which is more related to the interaction user interface with data.

In very complex scenarios, it might be better to separate validation from the view model and the view model and use both the view model and the data model.

+3
source share

All Articles