父子ValidationRule

时间:2012-08-03 20:32:11

标签: wpf validationrule

我有一个使用ValidationRules的复杂场景,我需要一些帮助。我有一个大致按此组织的用户控件:

Parent (ItemsControl)
    Child 1
        Property 1
        Property 2
    Child 2
        Property 1
        Property 2

当Child 1.Property 1更改时,我需要对其进行验证。但是,验证规则需要Child 1.Property 1的值以及其所有兄弟(变量号)的Property 1值来执行验证。我可以在父ItemsControl上放置一个ValidationRule,但我需要绑定到Child1.Property1的Control来显示错误。目前,当我将验证放在父级上时,错误显示在父级上,而不是子级上。我也考虑过使用BindingGroups,但我希望在更改属性时自动触发验证。据我所知,还没有一种方法可以自动强制Validation为BindingGroup触发。

有没有办法完成我想要做的事情?

1 个答案:

答案 0 :(得分:0)

这会自动将对象的所有数据注释属性转换为ValidationRule,并且可以在所有TextBox的应用中一次应用:

using System;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Controls;

using DaValidationResult = System.ComponentModel.DataAnnotations.ValidationResult;
using WinValidationResult = System.Windows.Controls.ValidationResult;

public sealed class DataAnnotationsBehavior
{
  public static bool GetValidateDataAnnotations(DependencyObject obj) =>
    (bool)obj.GetValue(ValidateDataAnnotationsProperty);
  public static void SetValidateDataAnnotations(DependencyObject obj, bool value) =>
    obj.SetValue(ValidateDataAnnotationsProperty, value);

  public static readonly DependencyProperty ValidateDataAnnotationsProperty =
      DependencyProperty.RegisterAttached("ValidateDataAnnotations", typeof(bool), 
        typeof(DataAnnotationsBehavior), new PropertyMetadata(false, OnPropertyChanged));

  private static void OnPropertyChanged(DependencyObject d, 
    DependencyPropertyChangedEventArgs e)
  {
    var boolean = (bool)e.NewValue;
    if (!(d is TextBox textBox))
      throw new NotSupportedException(
        @$"The behavior " +
        "'{typeof(DataAnnotationsBehavior)}' can only be applied " +
        "on elements of type '{typeof(TextBox)}'.");

    var bindingExpression =
      textBox.GetBindingExpression(TextBox.TextProperty);

    if (boolean)
    {
      var dataItem = bindingExpression.DataItem;
      if (bindingExpression.DataItem == null)
        return;

      var type = dataItem.GetType();
      var prop = type.GetProperty(bindingExpression.ResolvedSourcePropertyName);
      if (prop == null)
        return;

      var allAttributes = prop.GetCustomAttributes(typeof(ValidationAttribute), true);
      foreach (var validationAttr in allAttributes.OfType<ValidationAttribute>())
      {
        var context = new ValidationContext(dataItem, null, null) 
        { MemberName = bindingExpression.ResolvedSourcePropertyName };

        bindingExpression
          .ParentBinding
          .ValidationRules
          .Add(new AttributesValidationRule(context, validationAttr));
      }
    }
    else
    {
      var das =
        bindingExpression
          .ParentBinding
          .ValidationRules
          .OfType<AttributesValidationRule>()
          .ToList();

      if (das != null)
        foreach (var da in das)
          bindingExpression.ParentBinding.ValidationRules.Remove(da);
    }
  }

  abstract class DaValidationRule : ValidationRule
  {
    public ValidationContext ValidationContext { get; }

    public DaValidationRule(ValidationContext validationContext)
    {
      ValidationContext = validationContext;
    }
  }

  class AttributesValidationRule : DaValidationRule
  {
    public ValidationAttribute ValidationAttribute { get; }

    public AttributesValidationRule(ValidationContext validationContext, 
      ValidationAttribute attribute)
      : base(validationContext) =>
      ValidationAttribute = attribute;

    public override WinValidationResult Validate(object value, CultureInfo cultureInfo)
    {
      var result = ValidationAttribute.GetValidationResult(value, ValidationContext);

      return result == DaValidationResult.Success
        ? WinValidationResult.ValidResult
        : new WinValidationResult(false, result.ErrorMessage);
    }
  }
}

用法:

<Window.DataContext>
  <local:ViewModel />
</Window.DataContext>
<Window.Resources>
  <ResourceDictionary>
    <Style TargetType="TextBox">
      <Setter 
        Property="local:DataAnnotationsBehavior.ValidateDataAnnotations" 
        Value="True"/>
      <Style.Triggers>
        <Trigger Property="Validation.HasError" Value="True">
          <Setter 
            Property="ToolTip" 
            Value="{Binding (Validation.Errors)[0].ErrorContent,
              RelativeSource={RelativeSource Self}}"/>
        </Trigger>
      </Style.Triggers>
    </Style>
  </ResourceDictionary>
</Window.Resources>
<StackPanel DataContext="{Binding Model}">
  <TextBox Text="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</StackPanel>

我将DaValidationRule类抽象化是因为我认为将来可能会扩展它,因此它也涵盖了IValidationAttribute以及其他情况。

有关在编辑模式下涵盖TextBoxDataGridTextColumn个版本的版本,以及完整代码,请参见this