13

我已经阅读了很多关于 WPF 验证和DataAnnotations. 我想知道是否有一种干净的方式可以DataAnnotations用于ValidationRules我的实体。

因此,不要拥有这个(Source):

<Binding Path="Age" Source="{StaticResource ods}" ... >
  <Binding.ValidationRules>
    <c:AgeRangeRule Min="21" Max="130"/>
  </Binding.ValidationRules>
</Binding>

你必须有你的

public class AgeRangeRule : ValidationRule 
{...}

我希望 WPF 绑定去查看 Age 属性并寻找 DataAnnotation 有点像这样:

[Range(1, 120)]
public int Age
{
  get { return _age; }
  set
  {
    _age = value;
    RaisePropertyChanged<...>(x => x.Age);
  }
}

如果可能的话,有什么想法吗?

4

5 回答 5

8

我发现的最接近的方法是:

// This loop into all DataAnnotations and return all errors strings
protected string ValidateProperty(object value, string propertyName)
{
  var info = this.GetType().GetProperty(propertyName);
  IEnumerable<string> errorInfos =
        (from va in info.GetCustomAttributes(true).OfType<ValidationAttribute>()
         where !va.IsValid(value)
         select va.FormatErrorMessage(string.Empty)).ToList();


  if (errorInfos.Count() > 0)
  {
    return errorInfos.FirstOrDefault<string>();
  }
  return null;

来源

public class PersonEntity : IDataErrorInfo
{

    [StringLength(50, MinimumLength = 1, ErrorMessage = "Error Msg.")]
    public string Name
    {
      get { return _name; }
      set
      {
        _name = value;
        PropertyChanged("Name");
      }
    }

public string this[string propertyName]
    {
      get
      {
        if (porpertyName == "Name")
        return ValidateProperty(this.Name, propertyName);
      }
    }
}

来源来源

这样,DataAnnotation 工作正常,我在 XAML 上做的最少,ValidatesOnDataErrors="True"这是 Aaron post 与 DataAnnotation 的一个很好的解决方法。

于 2011-02-07T19:48:04.563 回答
5

在你的模型中,你可以实现IDataErrorInfo并做这样的事情......

string IDataErrorInfo.this[string columnName]
{
    get
    {
        if (columnName == "Age")
        {
            if (Age < 0 ||
                Age > 120)
            {
                return "You must be between 1 - 120";
            }
        }
        return null;
    }
}

您还需要通知绑定目标新定义的行为。

<TextBox Text="{Binding Age, ValidatesOnDataErrors=True}" />

编辑

如果您只想使用数据注释,您可以关注这篇博客文章,其中概述了如何完成任务。

更新

上述链接的历史表示。

于 2011-02-04T21:24:21.947 回答
0

听起来不错亚伦。我刚刚进入 WPF,下周将在工作中研究数据绑定;)所以不能完全判断你的答案......

但是对于 winforms,我使用了 Entlib 中的验证应用程序块,并在基本实体(业务对象)上实现了 IDataErrorInfo(实际上是IDXDataErrorInfo,因为我们使用的是 DevExpress 控件),并且效果很好!

它比您以这种方式绘制的解决方案要复杂一些,您将验证逻辑放在对象上而不是接口实现中。使其更具 OOP 和可维护性。在 ID(XD)ataErrorInfo 中,我只需调用 Validation.Validate(this),或者更好地获取调用接口的属性的验证器并验证特定的验证器。不要忘记调用 [SelfValidation] 因为属性组合的验证;)

于 2011-02-04T21:48:04.270 回答
0

您可能对WPF 应用程序框架 (WAF)的BookLibrary示例应用程序感兴趣。它使用 DataAnnotations Validation 属性和 WPF 绑定。

于 2011-02-05T15:27:34.253 回答
0

最近我有同样的想法,使用 Data Annotation API 来验证 WPF 中的 EF Code First POCO 类。像 Philippe 的帖子一样,我的解决方案使用反射,但所有必要的代码都包含在通用验证器中。

internal class ClientValidationRule : GenericValidationRule<Client> { }

internal class GenericValidationRule<T> : ValidationRule
{
  public override ValidationResult Validate(object value, CultureInfo cultureInfo)
  {
    string result = "";
    BindingGroup bindingGroup = (BindingGroup)value;
    foreach (var item in bindingGroup.Items.OfType<T>()) {
      Type type = typeof(T);
      foreach (var pi in type.GetProperties()) {
        foreach (var attrib in pi.GetCustomAttributes(false)) {
          if (attrib is System.ComponentModel.DataAnnotations.ValidationAttribute) {
            var validationAttribute = attrib as System.ComponentModel.DataAnnotations.ValidationAttribute;
            var val = bindingGroup.GetValue(item, pi.Name);
            if (!validationAttribute.IsValid(val)) { 
              if (result != "")
                result += Environment.NewLine;
              if (string.IsNullOrEmpty(validationAttribute.ErrorMessage))
                result += string.Format("Validation on {0} failed!", pi.Name);
              else
                result += validationAttribute.ErrorMessage;
            }
          }
        }
      }
    }
    if (result != "")
      return new ValidationResult(false, result);
    else 
      return ValidationResult.ValidResult;
  }
}

上面的代码显示了一个派生自通用 GenericValidationRule 类的 ClientValidatorRule。Client 类是我的 POCO 类,它将被验证。

public class Client {
    public Client() {
      this.ID = Guid.NewGuid();
    }

    [Key, ScaffoldColumn(false)]
    public Guid ID { get; set; }

    [Display(Name = "Name")]
    [Required(ErrorMessage = "You have to provide a name.")]
    public string Name { get; set; }
}
于 2013-12-12T21:56:59.087 回答