有没有办法将自定义验证错误添加到控件的错误列表中?我知道如何使用IDataErrorInfo,INotifyErrorInfo,ValidationAttribute等,但我想从代码中添加自定义验证错误。
答案 0 :(得分:0)
Found a way:
First, create a public class for holding our error message:
public class TagModelError { private readonly String errorMessage;
public TagModelError(String errorMessage)
{
this.errorMessage = errorMessage;
}
public Object Tag
{
get
{
return new Object();
}
set
{
throw new ValidationException(this.errorMessage);
}
}
}
Next, create a helper method:
public static void AddValidationError(this Control control, String errorMessage) { var expression = elm.GetBindingExpression(FrameworkElement.TagProperty);
if (expression == null)
{
expression = control.SetBinding(FrameworkElement.TagProperty, new Binding("Tag")
{
Mode = BindingMode.TwoWay,
ValidatesOnExceptions = true,
UpdateSourceTrigger = UpdateSourceTrigger.Explicit,
Source = new TagModelError(errorMessage)
}) as BindingExpression;
}
expression.UpdateSource();
}
I am using the Tag property because it is seldom required, but you can use another one. The trick here is to cause an exception when writing back to the model.