自定义 ValidationAttribute 不起作用。总是 returns 真
Custom ValidationAttribute doesn't work. Always returns true
我创建了一个自定义 ValidationAttribute class 来检查我的应用程序中某个人的年龄:
public class MinimumAgeAttribute : ValidationAttribute
{
public int MinAge { get; set; }
public override bool IsValid(object value)
{
return CalculateAge((DateTime) value) >= MinAge;
}
private int CalculateAge(DateTime dateofBirth)
{
DateTime today = DateTime.Now;
int age = today.Year - dateofBirth.Year;
if (dateofBirth > today.AddYears(-age)) age--;
return age;
}
}
字段上的数据标注是这样设置的:
[MinimumAge(MinAge = 18, ErrorMessage = "Person must be over the age of 18")]
public DateTime DateOfBirth;
我的 UI 中的绑定是这样设置的:
<DatePicker SelectedDate="{Binding SelectedPerson.DateOfBirth, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" Grid.Column="1"/>
例如,当我将日期(例如)设置为 09/06/2007 时,Validator.TryValidateObject
总是 returns true。
为什么?这似乎只影响我的自定义 classes,System.ComponentModel.DataAnnotations 中提供的所有那些都可以正常工作。
您的自定义 ValidationAttribute class 不起作用的原因是因为 WPF 在进行验证时不会(默认情况下)查看此类 classes。默认的验证机制是实现 IDataErrorInfo(适用于 .NET 4.0 及更早版本)或 INotifyDataErrorInfo(在 .NET 4.5 中引入)接口。如果你不想实现任何这些接口,那么你可以创建一个 ValidationRule,但我更喜欢实现上面提到的接口。
您可以在网上找到很多关于如何执行此操作的示例,但快速搜索后发现了这个 blog post(快速浏览后我觉得非常彻底)。
编辑
由于您似乎更热衷于使用数据注释而不是 IDataErrorInfo/INotifyDataErrorInfo 接口或验证规则,我认为 Microsoft TechNet 文章 "Data Validation in MVVM" 是使用数据注释进行验证的非常干净和彻底的实现.我自己通读了解决方案,并会推荐给其他人。
我创建了一个自定义 ValidationAttribute class 来检查我的应用程序中某个人的年龄:
public class MinimumAgeAttribute : ValidationAttribute
{
public int MinAge { get; set; }
public override bool IsValid(object value)
{
return CalculateAge((DateTime) value) >= MinAge;
}
private int CalculateAge(DateTime dateofBirth)
{
DateTime today = DateTime.Now;
int age = today.Year - dateofBirth.Year;
if (dateofBirth > today.AddYears(-age)) age--;
return age;
}
}
字段上的数据标注是这样设置的:
[MinimumAge(MinAge = 18, ErrorMessage = "Person must be over the age of 18")]
public DateTime DateOfBirth;
我的 UI 中的绑定是这样设置的:
<DatePicker SelectedDate="{Binding SelectedPerson.DateOfBirth, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" Grid.Column="1"/>
例如,当我将日期(例如)设置为 09/06/2007 时,Validator.TryValidateObject
总是 returns true。
为什么?这似乎只影响我的自定义 classes,System.ComponentModel.DataAnnotations 中提供的所有那些都可以正常工作。
您的自定义 ValidationAttribute class 不起作用的原因是因为 WPF 在进行验证时不会(默认情况下)查看此类 classes。默认的验证机制是实现 IDataErrorInfo(适用于 .NET 4.0 及更早版本)或 INotifyDataErrorInfo(在 .NET 4.5 中引入)接口。如果你不想实现任何这些接口,那么你可以创建一个 ValidationRule,但我更喜欢实现上面提到的接口。
您可以在网上找到很多关于如何执行此操作的示例,但快速搜索后发现了这个 blog post(快速浏览后我觉得非常彻底)。
编辑
由于您似乎更热衷于使用数据注释而不是 IDataErrorInfo/INotifyDataErrorInfo 接口或验证规则,我认为 Microsoft TechNet 文章 "Data Validation in MVVM" 是使用数据注释进行验证的非常干净和彻底的实现.我自己通读了解决方案,并会推荐给其他人。