Is there any way to add custom validation errors to the list of control's errors? I know how to use IDataErrorInfo, INotifyErrorInfo, ValidationAttribute, etc, but I would like to add custom validation errors from code.
Asked
Active
Viewed 72 times
1 Answers
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.

Ricardo Peres
- 13,724
- 5
- 57
- 74