title: WPF Validation Control
body: <p>I am new to WPF and trying to implement validation control on submit form. </p>
  
  <p>Can anyone help me. My code doen't show up any error message even if I enter invalid data infect it does nothing. </p>
  
  <p>Here is my code, </p>
  
  <pre><code> public partial class MainWindow : Window
  {
      public MainWindow()
      {
          InitializeComponent();
      }
  }
  
  
  public class UserName : INotifyPropertyChanged, IDataErrorInfo
  {
      public event PropertyChangedEventHandler PropertyChanged;
      public void OnPropertyChanged(PropertyChangedEventArgs e)
      {
          if (PropertyChanged != null)
              PropertyChanged(this, e);
      }
  
      private string username;
      public string _UserName
      {
          get { return username; }
          set
          {
              username = value;
              OnPropertyChanged(new PropertyChangedEventArgs("_UserName"));
          }
      }
      public string this[string propertyName]
      {
          get
          {
              if (propertyName == "_UserName")
              {
                  bool valid = true;
                  foreach (char c in _UserName)
                  {
                      if (!Char.IsLetterOrDigit(c))
                      {
                          valid = false;
                          break;
                      }
                  }
                  if (!valid)
                      return "The Username can only contain letters and numbers.";
              }
              return null;
          }
      }
      public string Error
      {
          get { return null; }
      }
  }
  </code></pre>
  
  <p>}
  My XAML code is,</p>
  
  <pre><code>&lt;Grid&gt;
      &lt;Label Content="User Name" Height="28" HorizontalAlignment="Left" Margin="27,37,0,0" Name="UserNameLB" VerticalAlignment="Top" Width="96" /&gt;
      &lt;TextBox Height="23" HorizontalAlignment="Left" Margin="135,37,0,0" Name="UserNameTB" VerticalAlignment="Top" Width="189"&gt;
          &lt;TextBox.Text&gt;
              &lt;Binding Path="_UserName"&gt;
                  &lt;Binding.ValidationRules&gt;
                      &lt;DataErrorValidationRule&gt;&lt;/DataErrorValidationRule&gt;
                  &lt;/Binding.ValidationRules&gt;
              &lt;/Binding&gt;
          &lt;/TextBox.Text&gt;
      &lt;/TextBox&gt;
  
  &lt;/Grid&gt;
  </code></pre>