user4681776
user4681776

Reputation:

How to successfully implement WPF textbox validation?

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

I used this guide: 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 is never triggered.

Upvotes: 3

Views: 7753

Answers (1)

Using what you posted, it works fine for me, it produces the red "!" above the textbox. However, I DID remember to set my DataContext, ie.

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

Without this, it won't work.

Upvotes: 6

Related Questions