1

我有一个使用 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 值来执行验证。我可以在 Parent ItemsControl 上放置一个 ValidationRule,但我需要将 Control 绑定到 Child1.Property1 以显示错误。目前,当我将验证放在父母身上时,错误会显示在父母身上,而不是孩子身上。我也考虑过使用 BindingGroups,但我希望在更改属性时自动触发验证。据我所知,没有一种方法可以自动强制 Validation 为 BindingGroup 触发。

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

4

1 回答 1

0

这会自动将所有对象的数据注解属性转为ValidationRules,并且可以在所有TextBoxes上的app中应用一次:

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,也许还有其他场景。

对于在编辑模式下涵盖TextBoxes的版本DataGridTextColumn,以及完整的代码,请参阅

于 2019-12-05T20:53:24.513 回答