I have a TextBox in my WPF app. I have defined a ControlTemplate for validation error as follows:
Validation.SetErrorTemplate(txtBox, this.FindResource("validationTemplate") as ControlTemplate);
For your first question. You can set the ErrorTemplate from code behind like.
public MainWindow()
{
InitializeComponent();
var template = this.FindResource("validationTemplate") as ControlTemplate;
Validation.SetErrorTemplate(this.textBox1, template);
}
Edit:
For your second question. Please refer the following sample.
sites.google.com/site/html5tutorials/ValidationErrorText.zip
Thanks to for the wonderful link he suggested me.My code goes somewhat this way
String errorMessage = GetFormattedErrorMessage(toolTip.Range, range);
ValidationError validationError = new ValidationError(new DummyValidator(),
txtBox.GetBindingExpression(TextBox.TextProperty));
Validation.MarkInvalid(txtBox.GetBindingExpression(TextBox.TextProperty), validationError);
validationError.ErrorContent = errorMessage;
Validation.SetErrorTemplate(txtBox, GetErrorTemplate(errorMessage));
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