我有一个简单的方法来解决这个特定问题。我创建了一个ValidationChecker
类,它将使用方法检查是否存在验证错误IsValid
。
public class ValidationChecker : Freezable
{
public static List<DependencyObject> elements = new List<DependencyObject>();
public static int GetValidationObject(DependencyObject obj)
{
return (int)obj.GetValue(ValidationObjectProperty);
}
public static void SetValidationObject(DependencyObject obj, int value)
{
obj.SetValue(ValidationObjectProperty, value);
}
// Using a DependencyProperty as the backing store for ErrorCount. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ValidationObjectProperty =
DependencyProperty.RegisterAttached("ValidationObject", typeof(DependencyObject), typeof(ValidationChecker), new PropertyMetadata(null, OnValueChanged));
public static bool IsValid()
{
foreach (var item in elements)
{
if (Validation.GetHasError(item)) return false;
}
return true;
}
private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
elements.Add(d);
}
protected override Freezable CreateInstanceCore()
{
return new ValidationChecker();
}
}
ValidationObject
附加属性可以如下实现
<DataTemplate>
<TextBox local:ValidationChecker.ValidationObject="{Binding RelativeSource={RelativeSource Self}}">
<TextBox.Text>
<Binding Path="Value">
<Binding.ValidationRules>
<local:NotEmptyValidationRule ValidatesOnTargetUpdated="True"></local:NotEmptyValidationRule>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
</DataTemplate>
您已经提到您的Button
已绑定到Command
. 所以实现and callCanExecute
的方法。不要忘记在需要时为此调用方法。Command
ValidationChecker.Isvalid()
RaiseCanExecute
Command