我在一个WPF应用程序中有一个文本框,它绑定到一个实现了IDataErrorInfo的Linq to Entities类的属性。该文本框绑定具有ValidatesOnExceptions=True和ValidatesOnDataErrors=True。当文本框绑定到整数属性并且用户输入文本时,文本框轮廓显示为红色,因为我没有设置自定义样式。
在我的保存方法中,如何知道对象无法保存,因为它无效?我希望用户单击保存按钮,我可以通知他们有问题,而不是禁用保存按钮。
谢谢,
Dave
我还没有找到一个简单的方法来实现它。我在网上找到了一些代码,可以递归遍历表单上的所有控件,并确定它们是否存在验证错误。最终我将其转化为了扩展方法:
// Validate all dependency objects in a window
internal static IList<ValidationError> GetErrors(this DependencyObject node)
{
// Check if dependency object was passed
if (node != null)
{
// Check if dependency object is valid.
// NOTE: Validation.GetHasError works for controls that have validation rules attached
bool isValid = !Validation.GetHasError(node);
if (!isValid)
{
// If the dependency object is invalid, and it can receive the focus,
// set the focus
if (node is IInputElement) Keyboard.Focus((IInputElement)node);
return Validation.GetErrors(node);
}
}
// If this dependency object is valid, check all child dependency objects
foreach (object subnode in LogicalTreeHelper.GetChildren(node))
{
if (subnode is DependencyObject)
{
// If a child dependency object is invalid, return false immediately,
// otherwise keep checking
var errors = GetErrors((DependencyObject)subnode);
if (errors.Count > 0) return errors;
}
}
// All dependency objects are valid
return new ValidationError[0];
}
因此,当用户在表单上点击保存按钮时,我会执行以下操作:
var errors = this.GetErrors();
if (errors.Count > 0)
{
MessageBox.Show(errors[0].ErrorContent.ToString());
return;
}
这比应该做的工作要多得多,但使用扩展方法可以简化一些。