How to use System.ComponentModel.DataAnnotations in a WPF or Winforms Application

is it possible to use System.ComponentModel.DataAnnotations and does it belong to an attribute (e.g. Required , Range , ...) in a WPF or Winforms class?

I want to put my check on attributes.

thanks

EDIT 1:

I am writing this:

 public class Recipe { [Required] [CustomValidation(typeof(AWValidation), "ValidateId", ErrorMessage = "nima")] public int Name { get; set; } } private void Window_Loaded(object sender, RoutedEventArgs e) { var recipe = new Recipe(); recipe.Name = 3; var context = new ValidationContext(recipe, serviceProvider: null, items: null); var results = new List<System.ComponentModel.DataAnnotations.ValidationResult>(); var isValid = Validator.TryValidateObject(recipe, context, results); if (!isValid) { foreach (var validationResult in results) { MessageBox.Show(validationResult.ErrorMessage); } } } public class AWValidation { public bool ValidateId(int ProductID) { bool isValid; if (ProductID > 2) { isValid = false; } else { isValid = true; } return isValid; } } 

but even I installed 3 in my property, nothing happened

+6
source share
1 answer

Yes you can . And here is another article illustrating this. You can do this even in a console application by manually creating a ValidationContext :

 public class DataAnnotationsValidator { public bool TryValidate(object @object, out ICollection<ValidationResult> results) { var context = new ValidationContext(@object, serviceProvider: null, items: null); results = new List<ValidationResult>(); return Validator.TryValidateObject( @object, context, results, validateAllProperties: true ); } } 

UPDATE:

Here is an example:

 public class Recipe { [Required] [CustomValidation(typeof(AWValidation), "ValidateId", ErrorMessage = "nima")] public int Name { get; set; } } public class AWValidation { public static ValidationResult ValidateId(int ProductID) { if (ProductID > 2) { return new ValidationResult("wrong"); } else { return ValidationResult.Success; } } } class Program { static void Main() { var recipe = new Recipe(); recipe.Name = 3; var context = new ValidationContext(recipe, serviceProvider: null, items: null); var results = new List<ValidationResult>(); var isValid = Validator.TryValidateObject(recipe, context, results, true); if (!isValid) { foreach (var validationResult in results) { Console.WriteLine(validationResult.ErrorMessage); } } } } 

Note that the ValidateId method must be public static and return a ValidationResult instead of boolean. Also note the fourth argument passed to the TryValidateObject method, which should be set to true if you want your custom validators to be evaluated.

+8
source

Source: https://habr.com/ru/post/893746/


All Articles