问题
In my MVVM based application I need to validate fields in a data entry from. If possible, I would like to use the standard WPF validation binding with ErrorTemplates.
However I would like the execution of the validation logic to be completely driven/triggered by the ViewModel (push to the View, not pull by the View) for the following reasons:
- It must work asynchronously because validation logic might take a while to execute.
- I need to be more deterministic and fine grained when validation logic is to be executed (e.g. only after the user clicks "Apply" or when the internal state changed in a way that entries suddenly become invalid)
I know Silverlight has INotifyDataErrorInfo
which was introduced for exactly this purpose, but WPF doesn't. How can I still have my validation logic exectuted deterministically and asynchronously?
回答1:
I posted an answer on your other question that apparently answered this one too.
Create a visualtree off of a control template in code
回答2:
The built in validation for WPF and Silverlight is meant for quick client-side validation (such as Regex, parsing values, etc.).
If you need to go to a server to perform validation (or validation takes a long time), I would do that in a custom way. Such as when clicking a save button, etc.
So say you have a Save method in a ViewModel (you don't mention which MVVM framework you use):
public void Save()
{
//Do your validation, this might start a new thread (I use Async CTP myself)
//If validation is good, do your extra work, else display validation errors
}
I would just do all the work required for this within an action in your ViewModel
来源:https://stackoverflow.com/questions/7281264/deterministic-and-asynchronous-field-validation-in-wpf