在WPF中,您可以使用ExceptionValidationRule
或DataErrorValidationRule
根据在数据绑定期间在数据层中引发的错误来设置验证。
假设你有一堆这样设置的控件,并且你有一个Save按钮。当用户单击save按钮时,您需要确保在继续保存之前没有验证错误。如果存在验证错误,您需要对其进行处理。
在WPF中,如何找出是否有任何数据绑定控件设置了验证错误?
发布于 2011-01-11 02:59:57
这篇文章非常有帮助。感谢所有做出贡献的人。这是一个你会喜欢或讨厌的LINQ版本。
private void CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = IsValid(sender as DependencyObject);
}
private bool IsValid(DependencyObject obj)
{
// The dependency object is valid if it has no errors and all
// of its children (that are dependency objects) are error-free.
return !Validation.GetHasError(obj) &&
LogicalTreeHelper.GetChildren(obj)
.OfType<DependencyObject>()
.All(IsValid);
}
发布于 2008-09-24 16:56:22
下面的代码(摘自Chris Sell和Ian Griffiths的Programming WPF一书)验证了依赖对象及其子对象上的所有绑定规则:
public static class Validator
{
public static bool IsValid(DependencyObject parent)
{
// Validate all the bindings on the parent
bool valid = true;
LocalValueEnumerator localValues = parent.GetLocalValueEnumerator();
while (localValues.MoveNext())
{
LocalValueEntry entry = localValues.Current;
if (BindingOperations.IsDataBound(parent, entry.Property))
{
Binding binding = BindingOperations.GetBinding(parent, entry.Property);
foreach (ValidationRule rule in binding.ValidationRules)
{
ValidationResult result = rule.Validate(parent.GetValue(entry.Property), null);
if (!result.IsValid)
{
BindingExpression expression = BindingOperations.GetBindingExpression(parent, entry.Property);
System.Windows.Controls.Validation.MarkInvalid(expression, new ValidationError(rule, expression, result.ErrorContent, null));
valid = false;
}
}
}
}
// Validate all the bindings on the children
for (int i = 0; i != VisualTreeHelper.GetChildrenCount(parent); ++i)
{
DependencyObject child = VisualTreeHelper.GetChild(parent, i);
if (!IsValid(child)) { valid = false; }
}
return valid;
}
}
您可以在保存按钮单击事件处理程序中调用此函数,如下所示
private void saveButton_Click(object sender, RoutedEventArgs e)
{
if (Validator.IsValid(this)) // is valid
{
....
}
}
发布于 2009-02-19 14:31:21
在使用ListBox时,发布的代码对我不起作用。我重写了它,现在它可以工作了:
public static bool IsValid(DependencyObject parent)
{
if (Validation.GetHasError(parent))
return false;
// Validate all the bindings on the children
for (int i = 0; i != VisualTreeHelper.GetChildrenCount(parent); ++i)
{
DependencyObject child = VisualTreeHelper.GetChild(parent, i);
if (!IsValid(child)) { return false; }
}
return true;
}
https://stackoverflow.com/questions/127477
复制相似问题