title: Setting Validation error template from code in WPF
body: <p>I have a TextBox in my WPF app. I have defined a ControlTemplate for validation error as follows: </p>
  
  <pre><code>&lt;ControlTemplate x:Key="validationTemplate"&gt;
      &lt;DockPanel LastChildFill="True"&gt;
           &lt;TextBlock DockPanel.Dock="Bottom"  Text="Invalid Input: "&gt;&lt;/TextBlock&gt;
                   &lt;AdornedElementPlaceholder /&gt;
      &lt;/DockPanel&gt;
  &lt;/ControlTemplate&gt;
  </code></pre>
  
  <p>My TextBox is as follows :</p>
  
  <pre><code>&lt;TextBox Validation.ErrorTemplate="{StaticResource validationTemplate}"&gt;                                              
      &lt;TextBox.Text&gt;
          &lt;Binding Path="TEXT1" ValidatesOnDataErrors="True" validatesOnExceptions="True"&gt;
           &lt;/Binding&gt;
      &lt;/TextBox.Text&gt;
  &lt;/TextBox&gt;
  </code></pre>
  
  <p>Now if my TextBox is added ValidationRule and then I validate there, the error template applies correctly. But I cant do that because of some other problem.</p>
  
  <p>So I have to validate the content of TextBox in PreviewLostKeyboardFocus. I am validating the TextBox. Now I want to set the error template for the TextBox in code behind but I am unable to do it !!</p>
  
  <p>I tried this but it does not work as intented::</p>
  
  <pre><code>private void blockTextBox_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
      {
          TextBox txtBox = sender as TextBox;
          txtBox.Template = this.FindResource("validationTemplate") as ControlTemplate;
  
          //this behaves strange; it removes the TextBox and places the ErrorTemplate. 
         //I want it to behave like the way WPF does internally wherein it places 
         //the error template around TExtBox
      }
  </code></pre>
  
  <p>Question 1: I want to know how to add the error template to TextBox<br></p>
  
  <p>Question 2: I want to know how do I set the error message of the control template from code. Like for example, I want to change the default error message "Invalid Input: " to "Invalid Input: Please enter correct input". <br>
  <br>
  <strong>I want to do the above mentioned things in code behind only !!!!</strong></p>
  
  <p><strong>EDIT 1:</strong></p>
  
  <p>The problem is how do I set from code behind Validation.HasError as true because I am not using any Validator. (or what should I set from code behind that ValidationTemplate gets applied ?? ))</p>
  
  <p><strong>EDIT 2:</strong></p>
  
  <p>I am doing XML binding so there is no way I can implement IDataErrorInfo !! I want to achieve this from code behind only!!  Is there a way to set Validation.HasError from code behind ??</p>