How to Use Model Validation Rules in WPF ViewModel

I'm using WPF with the MVVM pattern and just starting a very large project.

To keep concerns separated, I want to put all my validation rules into my data models.

But when I review how to do WPF validation, all the examples that I can find show how to do it with the ViewModel holding the validation rules. Some of these examples show some real deep understanding of WPF and are very cool.

In this particular app, I have a 1:1 mapping between the ViewModels that edit and models, so I could put it in the ViewModels. But it just doesn't feel right.


Validation using IDataErrorInfo (If that is what you are using) will occur on the object that is bound to on the View.

so if you have

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

this will be on the ViewModel. However if you expose the model as a property on the view model the validation will occur on your data model.

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

With the first choice, you can bind to the view model properties and route to the data model where it contains the actual validation, then just implement IDataErrorInfo on the view model and route the validation to the model

ViewModel:

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

This is useful only if you actually set the required properties on the model for the validation to work

ViewModel:

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

However I prefer the second binding option becasuse the problem with this is that it is not very DRY, so I will almost always expose the DataModel as a property on the view model (as that is responsible for the data) and leave the ViewModel managing the model for the view, which is more about how the UI interacts with the data.

In very complex scenarios, it may be better to separate the validation from the model and viewmodel and have both the view model and data model consume it.

链接地址: http://www.djcxy.com/p/3430.html

上一篇: SproutCore Ace for jQueryUI

下一篇: 如何在WPF ViewModel中使用模型验证规则