I have a TextBox in my WPF app. I have defined a ControlTemplate for validation error as follows:
To set "Validation.HasError" in code behind you can use the Validation.MarkInvalid method
private void blockTextBox_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
TextBox txtBox = sender as TextBox;
//...
BindingExpression bindingExpression =
BindingOperations.GetBindingExpression(txtBox, TextBox.TextProperty);
BindingExpressionBase bindingExpressionBase =
BindingOperations.GetBindingExpressionBase(txtBox, TextBox.TextProperty);
ValidationError validationError =
new ValidationError(new ExceptionValidationRule(), bindingExpression);
Validation.MarkInvalid(bindingExpressionBase, validationError);
}
To unset the value you use
Validation.ClearInvalid