14

Is there any way to manually/dynamically add errors to the Validation.Errors collection?

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
john doe
  • 141
  • 1
  • 4
  • Here is a good (a little more detailed) answer: http://stackoverflow.com/questions/4273899/setting-validation-error-template-from-code-in-wpf – Tal Segal Sep 22 '13 at 08:47

2 Answers2

24

from http://www.wpftutorial.net/ValidationErrorByCode.html

ValidationError validationError = new ValidationError(regexValidationRule, 
    textBox.GetBindingExpression(TextBox.TextProperty));

validationError.ErrorContent = "This is not a valid e-mail address";

Validation.MarkInvalid(
    textBox.GetBindingExpression(TextBox.TextProperty), 
    validationError);
jrwren
  • 17,465
  • 8
  • 35
  • 56
1

jrwren's answer guided me in the right direction, but wasn't very clear as to what regexValidationRule was nor how to clear the validation error. Here's the end result I came up with.

I chose to use Tag since I was using this manual validation in a situation where I wasn't actually using a viewmodel or bindings. This gave something I could bind to without worrying about affecting the view.

Adding a binding in code behind:

private void AddValidationAbility(FrameworkElement uiElement)
{
  var binding = new Binding("TagProperty");
  binding.Source = this;

  uiElement.SetBinding(FrameworkElement.TagProperty, binding);
}

and trigging a validation error on it without using IDataError:

using System.Windows;
using System.Windows.Controls;

    private void UpdateValidation(FrameworkElement control, string error)
    {
      var bindingExpression = control.GetBindingExpression(FrameworkElement.TagProperty);

      if (error == null)
      {
        Validation.ClearInvalid(bindingExpression);
      }
      else
      {
        var validationError = new ValidationError(new DataErrorValidationRule(), bindingExpression);
        validationError.ErrorContent = error;
        Validation.MarkInvalid(bindingExpression, validationError);
      }
    }
Bill Tarbell
  • 4,933
  • 2
  • 32
  • 52