5
我喜歡企業庫中的驗證應用程序塊:-)
現在我想在Winforms中使用DataAnnotations,因爲我們也使用了asp.net動態數據。所以我們對整個公司都有共同的技術。
而且數據註釋應該更易於使用。如何在Winforms中使用數據註釋驗證器?
我該如何做類似Stephen Walter did within asp.net MVC的Winforms?
我喜歡企業庫中的驗證應用程序塊:-)
現在我想在Winforms中使用DataAnnotations,因爲我們也使用了asp.net動態數據。所以我們對整個公司都有共同的技術。
而且數據註釋應該更易於使用。如何在Winforms中使用數據註釋驗證器?
我該如何做類似Stephen Walter did within asp.net MVC的Winforms?
我適應找到了解決辦法,在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中實現 – 2009-03-04 23:05:46