我在WPF应用程序中有一个文本框绑定到实现IDataErrorInfo的Linq to Entities类上的属性.文本框绑定具有ValidatesOnExceptions = True和ValidatesOnDataErrors = True.当文本框绑定到整数属性并且用户输入文本时,文本框轮廓显示为红色,因为我没有设置自定义样式.
在我的保存方法中,我怎么知道对象无法保存,因为它无效?我希望用户单击"保存"按钮,我可以通知他们问题,而不是禁用"保存"按钮.
干杯,
戴夫
我还没有找到一个简单的方法来做到这一点.我在陷阱周围找到了一些代码来递归表单上的所有控件,并确定它们中是否有任何验证错误.我最终把它变成了一个扩展方法:
// 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];
}
Run Code Online (Sandbox Code Playgroud)
那么当用户单击表单上的"保存"按钮时,我这样做:
var errors = this.GetErrors();
if (errors.Count > 0)
{
MessageBox.Show(errors[0].ErrorContent.ToString());
return;
}
Run Code Online (Sandbox Code Playgroud)
这比它应该做的工作多得多,但使用扩展方法可以简化它.
| 归档时间: |
|
| 查看次数: |
2739 次 |
| 最近记录: |