How to successfully implement WPF textbox validation?

I'm trying to implement what a simple textbox validation should be for a WPF application, but I'm having some problems.

I used this tutorial: http://www.codeproject.com/Tips/690130/Simple-Validation-in-WPF

My textbox in MainWindow.xaml:

     <TextBox x:Name="textbox1" HorizontalAlignment="Left" Height="23" 
             Margin="93,111,0,0" TextWrapping="Wrap" VerticalAlignment="Top" 
             Width="120" Style="{StaticResource textBoxInError}"
             Validation.ErrorTemplate="{StaticResource validationErrorTemplate}">
        <TextBox.Text>
            <Binding Path="Name" UpdateSourceTrigger="PropertyChanged">
                <Binding.ValidationRules>
                    <local:NameValidator/>
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>
    </TextBox>

      

My NameValidator Class in MainWindow.xaml.cs:

    public class NameValidator : ValidationRule 
    {
      public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
      {
        if (value == null)
            return new ValidationResult(false, "value cannot be empty.");
        else
        {
            if (value.ToString().Length > 3)
                return new ValidationResult(false, "Name cannot be more than 3 characters long.");
        }
        return ValidationResult.ValidResult;
      }
  }

      

My static resources in App.xaml:

        <ControlTemplate x:Key="validationErrorTemplate">
            <DockPanel>
                <TextBlock Foreground="Red" DockPanel.Dock="Top">!</TextBlock>
                <AdornedElementPlaceholder x:Name="ErrorAdorner"></AdornedElementPlaceholder>
            </DockPanel>
        </ControlTemplate>
        <Style x:Key="textBoxInError" TargetType="{x:Type TextBox}">
            <Style.Triggers>
                <Trigger Property="Validation.HasError" Value="true">
                    <Setter Property="ToolTip"
                            Value="{Binding RelativeSource={x:Static RelativeSource.Self},
                            Path=(Validation.Errors)[0].ErrorContent}"/>
                </Trigger>
            </Style.Triggers>
        </Style>

      

I can run the application without any errors, but the validation fails.

+3


source to share


1 answer


Using what you posted it works great for me, it creates a red "!" above the text box. However, I did not forget to set my DataContext i.e.

public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this;
    }

      



Without that, it won't work.

+5


source







All Articles