WPF Binding : Use DataAnnotations for ValidationRules

前端 未结 5 569
眼角桃花
眼角桃花 2020-12-09 04:59

I have read a lot of Blog post on WPF Validation and on DataAnnotations. I was wondering if there is a clean way to use DataAnnotations as Va

5条回答
  •  孤城傲影
    2020-12-09 05:37

    The closest approach I found is :

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

    Source

    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);
          }
        }
    }
    

    Source and Source

    That way, the DataAnnotation works fine, I got a minimum to do on the XAML ValidatesOnDataErrors="True" and it's a fine workaround of Aaron post with the DataAnnotation.

提交回复
热议问题