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.

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...