Ari*_*ian 7 c# validation wpf winforms c#-4.0
是否有可能使用System.ComponentModel.DataAnnotations,它是属于属性(例如Required,Range在WPF或的WinForms类,...)?
我想把我的验证放到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;
}
}
Run Code Online (Sandbox Code Playgroud)
但即使我将3设置为我的财产也没有发生任何事情
是的,你可以.这是另一篇说明这一点的文章.您甚至可以通过手动创建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
);
}
}
Run Code Online (Sandbox Code Playgroud)
更新:
这是一个例子:
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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,该ValidateId方法必须是public static并返回ValidationResult 而不是boolean.另请注意传递给TryValidateObject方法的第四个参数,如果希望计算自定义验证器,则必须将其设置为true.