【问题标题】:How to use Data Annotation Validators in Winforms?如何在 Winforms 中使用数据注释验证器?
【发布时间】:2008-12-16 09:47:44
【问题描述】:

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

如何在 Winforms 中做类似的事情,例如 Stephen Walter did within asp.net MVC

【问题讨论】:

    标签: asp.net-mvc winforms data-annotations


    【解决方案1】:

    我改编了在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));
        }
    }
    

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

    var errors = DataValidator.Validate(obj);
    
    if (errors.Any()) throw new ValidationException();
    

    【讨论】:

    • 我喜欢这样。必须尝试一下,但看起来它可以完成工作......对 Validate() 的手动调用不是很好,但我们可以通过在 UserControls 中实现它来避免这种情况
    • 你的 Validate() 不能用 System.ComponentModel.DataAnnotations.Validator 代替吗?
    • @Rolf:仅在 Silverlight 或 .Net 4+ 中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-24
    • 1970-01-01
    • 2021-01-16
    • 2011-03-25
    相关资源
    最近更新 更多