Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use System.ComponentModel.DataAnnotations in WPF or Winforms application

is it possible to use System.ComponentModel.DataAnnotations and it's belong attribute(such as Required,Range,...) in WPF or Winforms class?

I want put my validation to attributs.

thanks

EDIT 1:

I write 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 set 3 to my property nothing happend

like image 574
Arian Avatar asked Jul 28 '11 06:07

Arian


People also ask

How do I use system ComponentModel DataAnnotations?

Data annotations (available as part of the System. ComponentModel. DataAnnotations namespace) are attributes that can be applied to classes or class members to specify the relationship between classes, describe how the data is to be displayed in the UI, and specify validation rules.

What is DataAnnotations in C#?

DataAnnotations namespace includes the following validator attributes: Range – Enables you to validate whether the value of a property falls between a specified range of values. RegularExpression – Enables you to validate whether the value of a property matches a specified regular expression pattern.

Which static class from the system ComponentModel DataAnnotations namespace can be used to validate objects properties and methods?

ValidationAttribute Class (System. ComponentModel. DataAnnotations) Serves as the base class for all validation attributes.

How does required attribute work C#?

RequiredAttribute , like all other attributes, does nothing by itself other than annotate something (in this case, a field of a type). It is entirely up to the application that consumes the type to detect the presence of the attribute and respond accordingly.


1 Answers

Yes, you can. And here's another article illustrating this. You could 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's 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);
            }
        }
    }
}

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

like image 174
Darin Dimitrov Avatar answered Oct 11 '22 08:10

Darin Dimitrov