2008-12-16 29 views
5

Tôi thích Khối ứng dụng xác nhận từ Thư viện doanh nghiệp :-)
Bây giờ tôi muốn sử dụng DataAnnotations trong Winforms, vì chúng tôi cũng sử dụng Dữ liệu động asp.net. Vì vậy, chúng tôi có công nghệ chung trên toàn bộ công ty.
Đồng thời, chú thích dữ liệu sẽ dễ sử dụng hơn.Cách sử dụng Trình xác thực chú thích dữ liệu trong Winforms?

Làm cách nào tôi có thể làm điều gì đó tương tự trong Winforms như Stephen Walter did within asp.net MVC?

Trả lời

9

tôi chuyển thể một giải pháp tìm thấy tại 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)); 
    } 
} 

này sẽ cho phép bạn sử dụng đoạn mã sau để xác nhận bất kỳ đối tượng bằng cách sử dụng cú pháp sau:

var errors = DataValidator.Validate(obj); 

if (errors.Any()) throw new ValidationException(); 
+0

tôi thích điều đó. Phải thử nó, nhưng có vẻ như nó thực hiện công việc ... Cuộc gọi thủ công tới Validate() không tốt lắm, nhưng chúng ta có thể tránh điều này, bằng cách thực hiện điều đó trong UserControls –

+0

của bạn. được thay thế bằng System.ComponentModel.DataAnnotations.Validator? –

+0

@Rolf: Chỉ trong Silverlight hoặc .Net 4+ – Darbio

Các vấn đề liên quan