如何使用IDataErrorInfo从ViewModel强制在View上更新验证错误? [英] How to force validation errors update on View from ViewModel using IDataErrorInfo?

查看:119
本文介绍了如何使用IDataErrorInfo从ViewModel强制在View上更新验证错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基于MVVM的窗口,其中包含许多控件,并且我的模型实现了IDataErrorInfo.

I have a MVVM-based Window with many controls, and my Model implements IDataErrorInfo.

还有一个SaveCommand按钮,该按钮通过分析Model.Error属性执行验证.

There is also a SaveCommand button, which performs validation by analysing Model.Error property.

仅当我更改特定控件的值或使用PropertyChanged通知该属性的更改时,视图才会在控件周围显示默认的红色边框,并带有错误.

The view displays the default red border around controls with errors only when I change the value of a particular control, or when I notify about the change of that property using PropertyChanged.

即使我没有触摸控件,如何强制View显示所有验证错误?

我所有的验证绑定都包括ValidatesOnDataErrors=True, NotifyOnValidationError=True.

All my validation bindings include ValidatesOnDataErrors=True, NotifyOnValidationError=True.

我知道一种解决方案是让所有错误都显示在一个聚合框中,但是我希望按控件显示错误.

I know one solution is to have an aggregate box with all the errors, but I would prefer to display errors on per-control basis.

我不想为ViewModel中的每个绑定属性触发Model.NotifyPropertyChanged.

I don't want to trigger Model.NotifyPropertyChanged for each bound property from ViewModel.

我使用的是WPF 4.0,而不是Silverlight,所以INotifyDataErrorInfo无法正常工作.

I use WPF 4.0, not Silverlight, so INotifyDataErrorInfo won't work.

推荐答案

您提到您不想提高绑定到的属性的属性,但这实际上是最简单的方法.调用不带参数的PropertyChanged将引发视图模型中的所有属性.

You mention that you don't want to raise property changed for the properties you bind to, but that's really the simplest way to accomplish this. Calling PropertyChanged with no parameter will raise for all properties in your viewmodel.

或者,您可以像这样在任何控件上更新绑定(并强制重新验证):

Alternatively you can update the bindings (and force revalidation) on any control like this:

myControl.GetBindingExpression(ControlType.ControlProperty).UpdateSource();

这篇关于如何使用IDataErrorInfo从ViewModel强制在View上更新验证错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆