Adding Custom Validation Messages in Silverlight
Sometimes it is useful to add our own validation messages to a Silverlight control, normally because we are doing custom validation through code, not through the reguar IDataErrorInfo, INotifyDataErrorInfo or ValidationAttributes. This is not straightforward, but it is possible. An example might be:
//this class is used for throwing an exception upon binding
//has to be public, doesn't need to implement any interfaces
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);
}
}
}
//extension method for adding validation messages on a control
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();
}
In this example I am using the TagProperty, because it is seldom used, but you can use whatever you like. The trick here is to force the update of a bound object, which throws an exception, which in turn is propagated as a validation error.