是否可以在wpf或winforms类中使用System.ComponentModel.DataAnnotations及其属性(如RequiredRange,…)?
我想把我的确认归功于属性。
谢谢
编辑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

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。

关于c# - 如何在WPF或Winforms应用程序中使用System.ComponentModel.DataAnnotations,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6854759/

10-13 06:44