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

时间:2011-07-28 06:13:30

标签: c# wpf winforms validation c#-4.0

是否可以在WPF或Winforms类中使用System.ComponentModel.DataAnnotations及其所属属性(例如RequiredRange,...)?

我想把我的验证放到attributs。

感谢

编辑1:

我写这个:

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;
    }        
}

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

1 个答案:

答案 0 :(得分:8)

是的,you can。这里有another article说明这一点。您甚至可以通过手动创建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
        );
    }
}

更新:

以下是一个例子:

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);
            }
        }
    }
}

请注意,ValidateId方法必须是public static并返回ValidationResult而不是boolean。另请注意传递给TryValidateObject方法的第四个参数,如果要对自定义验证器进行求值,则必须将其设置为true。