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

发布于 2024-07-10 14:08:08 字数 346 浏览 10 评论 0原文

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

我怎样才能在Winforms中做类似的事情,例如 Stephen Walter 在 asp.net MVC 中做了什么

I like the Validation Application Block from the Enterprise Library :-)
Now i would like to use the DataAnnotations in Winforms, as we use asp.net Dynamic Data as well. So that we have common technologies over the whole company.
And also the Data Annotations should be easier to use.

How can I do something similiar in Winforms like Stephen Walter did within asp.net MVC?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

冷月断魂刀 2024-07-17 14:08:08

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

I adapted a solution found at 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));
    }
}

This would allow you to use the following code to validate any object using the following syntax:

var errors = DataValidator.Validate(obj);

if (errors.Any()) throw new ValidationException();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文