如何在Winforms中使用数据注释验证器?

Pet*_*der 5 asp.net-mvc winforms data-annotations

我喜欢企业库中的验证应用程序块:-)
现在我想在Winforms中使用DataAnnotations,因为我们也使用asp.net动态数据.因此,我们在整个公司拥有共同的技术.
此外,数据注释应该更容易使用.

我怎样才能在像Stephen Walter在asp.net MVC中那样在Winforms中做类似的事情?

Mat*_*ell 9

我改编了一个在http://blog.codeville.net/category/validation/page/2/找到的解决方案

public class DataValidator
    {
    public class ErrorInfo
    {
        public ErrorInfo(string property, string message)
        {
            this.Property = property;
            this.Message = message;
        }

        public string Message;
        public string Property;
    }

    public static IEnumerable<ErrorInfo> Validate(object instance)
    {
        return from prop in instance.GetType().GetProperties()
               from attribute in prop.GetCustomAttributes(typeof(ValidationAttribute), true).OfType<ValidationAttribute>()
               where !attribute.IsValid(prop.GetValue(instance, null))
               select new ErrorInfo(prop.Name, attribute.FormatErrorMessage(string.Empty));
    }
}
Run Code Online (Sandbox Code Playgroud)

这将允许您使用以下代码使用以下语法验证任何对象:

var errors = DataValidator.Validate(obj);

if (errors.Any()) throw new ValidationException();
Run Code Online (Sandbox Code Playgroud)