c# – 如何在WPF或Winforms应用程序中使用System.ComponentModel.DataAnnotations

前端之家收集整理的这篇文章主要介绍了c# – 如何在WPF或Winforms应用程序中使用System.ComponentModel.DataAnnotations前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
是否可以在 WPFWinforms类中使用System.ComponentModel.DataAnnotations并且它属于属性(例如required,Range,…)?

我想把我的验证放到attributs上.

谢谢

编辑1:

我写这个:

  1. public class Recipe
  2. {
  3. [required]
  4. [CustomValidation(typeof(AWValidation),"ValidateId",ErrorMessage = "nima")]
  5. public int Name { get; set; }
  6. }
  7.  
  8. private void Window_Loaded(object sender,RoutedEventArgs e)
  9. {
  10. var recipe = new Recipe();
  11. recipe.Name = 3;
  12. var context = new ValidationContext(recipe,serviceProvider: null,items: null);
  13. var results = new List<System.ComponentModel.DataAnnotations.ValidationResult>();
  14.  
  15. var isValid = Validator.TryValidateObject(recipe,context,results);
  16.  
  17. if (!isValid)
  18. {
  19. foreach (var validationResult in results)
  20. {
  21. MessageBox.Show(validationResult.ErrorMessage);
  22. }
  23. }
  24. }
  25.  
  26. public class AWValidation
  27. {
  28. public bool ValidateId(int ProductID)
  29. {
  30. bool isValid;
  31.  
  32. if (ProductID > 2)
  33. {
  34. isValid = false;
  35. }
  36. else
  37. {
  38. isValid = true;
  39. }
  40.  
  41. return isValid;
  42. }
  43. }

但即使我将3设置为我的财产也没有发生任何事情

解决方法

是的,you can.这是 another article说明这一点.您甚至可以通过手动创建 ValidationContext在控制台应用程序中执行此操作:
  1. public class DataAnnotationsValidator
  2. {
  3. public bool TryValidate(object @object,out ICollection<ValidationResult> results)
  4. {
  5. var context = new ValidationContext(@object,items: null);
  6. results = new List<ValidationResult>();
  7. return Validator.TryValidateObject(
  8. @object,results,validateAllProperties: true
  9. );
  10. }
  11. }

更新:

这是一个例子:

  1. public class Recipe
  2. {
  3. [required]
  4. [CustomValidation(typeof(AWValidation),ErrorMessage = "nima")]
  5. public int Name { get; set; }
  6. }
  7.  
  8. public class AWValidation
  9. {
  10. public static ValidationResult ValidateId(int ProductID)
  11. {
  12. if (ProductID > 2)
  13. {
  14. return new ValidationResult("wrong");
  15. }
  16. else
  17. {
  18. return ValidationResult.Success;
  19. }
  20. }
  21. }
  22.  
  23. class Program
  24. {
  25. static void Main()
  26. {
  27. var recipe = new Recipe();
  28. recipe.Name = 3;
  29. var context = new ValidationContext(recipe,items: null);
  30. var results = new List<ValidationResult>();
  31.  
  32. var isValid = Validator.TryValidateObject(recipe,true);
  33.  
  34. if (!isValid)
  35. {
  36. foreach (var validationResult in results)
  37. {
  38. Console.WriteLine(validationResult.ErrorMessage);
  39. }
  40. }
  41. }
  42. }

请注意,ValidateId方法必须是public static并返回ValidationResult而不是boolean.另请注意传递给TryValidateObject方法的第四个参数,如果希望计算自定义验证器,则必须将其设置为true.

猜你在找的C#相关文章