我读了很多关于WPF验证和DataAnnotations的博客文章。我想知道是否有一种干净的方法来使用DataAnnotations作为我的实体的ValidationRules。
因此,不使用这个(Source):
<Binding Path="Age" Source="{StaticResource ods}" ... >
<Binding.ValidationRules>
<c:AgeRangeRule Min="21" Max="130"/>
</Binding.ValidationRules>
</Binding>在那里你必须有你的
public class AgeRangeRule : ValidationRule
{...}我想让WPF绑定去查看Age属性,并像这样查找DataAnnotation:
[Range(1, 120)]
public int Age
{
get { return _age; }
set
{
_age = value;
RaisePropertyChanged<...>(x => x.Age);
}
}如果这是可能的,有什么想法吗?
发布于 2011-02-08 03:48:05
我找到的最接近的方法是:
// This loop into all DataAnnotations and return all errors strings
protected string ValidateProperty(object value, string propertyName)
{
var info = this.GetType().GetProperty(propertyName);
IEnumerable<string> errorInfos =
(from va in info.GetCustomAttributes(true).OfType<ValidationAttribute>()
where !va.IsValid(value)
select va.FormatErrorMessage(string.Empty)).ToList();
if (errorInfos.Count() > 0)
{
return errorInfos.FirstOrDefault<string>();
}
return null;Source
public class PersonEntity : IDataErrorInfo
{
[StringLength(50, MinimumLength = 1, ErrorMessage = "Error Msg.")]
public string Name
{
get { return _name; }
set
{
_name = value;
PropertyChanged("Name");
}
}
public string this[string propertyName]
{
get
{
if (porpertyName == "Name")
return ValidateProperty(this.Name, propertyName);
}
}
}Source和Source
这样,DataAnnotation就可以很好地工作了,我在XAML ValidatesOnDataErrors="True"上做了最少的事情,这是Aaron post在DataAnnotation上的一个很好的变通方法。
发布于 2011-02-05 05:24:22
在您的模型中,您可以实现IDataErrorInfo并执行以下操作...
string IDataErrorInfo.this[string columnName]
{
get
{
if (columnName == "Age")
{
if (Age < 0 ||
Age > 120)
{
return "You must be between 1 - 120";
}
}
return null;
}
}您还需要将新定义的行为通知绑定目标。
<TextBox Text="{Binding Age, ValidatesOnDataErrors=True}" />编辑:
如果您只想使用数据注释,您可以遵循这个blog post,它概述了如何完成任务。
更新
发布于 2011-02-05 05:48:04
听起来不错亚伦。我刚刚进入WPF,下周将在工作中学习数据库绑定;)所以我不能完全判断你的答案……
但在winforms中,我使用了Validation Application Block from the Entlib,并在一个基本实体(业务对象)上实现了IDataErrorInfo (实际上是IDXDataErrorInfo,因为我们使用DevExpress控件),这非常好用!
它比您用这种方式勾勒出的解决方案要复杂一些,即您将验证逻辑放在对象上,而不是放在接口实现中。使其更具面向对象和可维护性。在ID(XD)处,我只需调用Validation.Validate(AtaErrorInfo),或者更好地获取调用接口的属性的验证器,并验证特定的验证器。不要忘了调用SelfValidation,因为要验证属性的组合;)
https://stackoverflow.com/questions/4903047
复制相似问题