Using Validation In WPF With Dependency Property And Style Triggers

- 1 answer

I am trying to use Validation in WPF. I created a NotNullOrEmptyValidationRule as shown below:

public class NotNullOrEmptyValidationRule : ValidationRule
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
            if (String.IsNullOrEmpty(value as String))
                return new ValidationResult(false, "Value cannot be null or empty");

            return new ValidationResult(true, null); 

Now, I need to use it in my application. In my App.xaml file I declared the Style for the TextBox. Here is the declaration.

 <Style x:Key="textBoxStyle" TargetType="{x:Type TextBox}">

            <Setter Property="Background" Value="Green"/>


                <Trigger Property="Validation.HasError" Value="True">

                    <Setter Property="Background" Value="Red"/>
                    <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self},Path=(Validation.Errors)[0].ErrorContent}"/>




Now, I want to use it on my TextBox so I am using the following code:

  <TextBox Style="{StaticResource textBoxStyle}">
                            <NotNullOrEmptyValidationRule />


The error comes on the Tag NotNullOrEmptyValidationRule. The XAML syntax checker is not able to resolve the NotNullOrEmptyValidationRule. I have even tried putting the namespace but it does not seem to work.



i see your binding on the TextBox is set to a path of 'Text' - is that a field on whatever the datacontext of this textbox is? is the textbox actually getting a value put into it? also, if you put a breakpoint in your validation method, is that ever getting fired?

you may want to lookup how to log failures in binding and review those as well..