title: Canceling TextBox input on validation error in WPF
body: <p>I'm trying to figure out how to cancel user input in a <code>TextBox</code> when a validation error occurs. If the user attempts to enter an invalid character I would like to prevent it from being added to the <code>TextBox</code>.</p>
  
  <p>How can I add to or modify the code below to prevent the <code>TextBox</code> from accepting invalid characters? Is it possible without listening to the <code>TextBox.TextChanged</code> event?</p>
  
  <p>My <code>TextBox</code> looks like:</p>
  
  <pre><code>&lt;TextBox Validation.Error="OnSomeTextBoxValidationError"&gt;
      &lt;TextBox.Text&gt;
          &lt;Binding Path="Value" NotifyOnValidationError="True" UpdateSourceTrigger="PropertyChanged"&gt;
              &lt;Binding.ValidationRules&gt;
                   &lt;local:SomeValidationRule /&gt;
              &lt;/Binding.ValidationRules&gt;
          &lt;/Binding&gt;
      &lt;/TextBox.Text&gt;
  &lt;/TextBox&gt;
  </code></pre>
  
  <p>My custom validation rule looks like:</p>
  
  <pre><code>public class SomeValidationRule : ValidationRule
  {
      public override ValidationResult Validate(object value, CultureInfo cultureInfo)
      {
          string hex_string = value as string;
          Match invalid_chars = Regex.Match(hex_string, "[^0-9a-fA-F]");
          bool is_valid = (invalid_chars.Success == false);
          string error_context = null;
  
          if (is_valid == false)
          {
              error_context = "Invalid characters";
          }
  
          return new ValidationResult(is_valid, error_context);
      }
  }
  </code></pre>
  
  <p>I have an error handler... can I do anything with it?</p>
  
  <pre><code>private void OnSomeTextBoxValidationError(object sender, ValidationErrorEventArgs e)
  {
      // Can I do anything here?
  }
  </code></pre>
  
  <p>Please provide an original answer if possible, rather than referring to a URL. I've read a lot of possible solutions involving event handlers, but I haven't come across anyone discussing the possibility of doing all my validation in the <code>ValidationRule</code>.</p>