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

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

我想把我的验证放到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设置为我的财产也没有发生任何事情

解决方法

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

更新:

这是一个例子:

public class Recipe
{
    [required]
    [CustomValidation(typeof(AWValidation),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,items: null);
        var results = new List<ValidationResult>();

        var isValid = Validator.TryValidateObject(recipe,true);

        if (!isValid)
        {
            foreach (var validationResult in results)
            {
                Console.WriteLine(validationResult.ErrorMessage);
            }
        }
    }
}

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

原文链接:https://www.f2er.com/csharp/244504.html

猜你在找的C#相关文章