onefootswill
onefootswill

Reputation: 4077

Validation.Error is not Invoking Handler

I’m having some problems with validation. I have created a custom validator called RequiredFieldRule which is applied in the xaml as follows:

<TextBox local:Masking.Mask="^[a-zA-Z0-9]*$" x:Name="CameraIdCodeTextBox" Grid.Row="1" Grid.Column="1">
<Binding Path="CameraIdCode" Mode="TwoWay">
  <Binding.ValidationRules>
    <localValidation:RequiredFieldRule />
</Binding.ValidationRules>
</Binding>
</TextBox>

That validator returns the following, when a user moves away from that TextBox without entering a value:

return new ValidationResult(false, ValidationFailedMessage);

I want to show some custom visual feedback and have attempted to use the Validation.Error event to capture the error as it bubbles up:

    private void Grid_Error(object sender, ValidationErrorEventArgs e)
    {
        // do stuff here

    }

Unfortunately, that handler is never invoked. My question is, why is that handler not invoked, when the TextBox inside it correctly returns a failed ValidationResult?

Upvotes: 2

Views: 1295

Answers (1)

Rhyous
Rhyous

Reputation: 6680

You don't have everything you need set in the XAML. Try adding these XAML properties:

  • UpdateSourceTrigger="PropertyChanged"
  • NotifyOnValidationError="True"
  • ValidatesOnExceptions="True"

Like this:

<TextBox local:Masking.Mask="^[a-zA-Z0-9]*$" x:Name="CameraIdCodeTextBox" Grid.Row="1" Grid.Column="1">
<Binding Path="CameraIdCode" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" NotifyOnValidationError="True" ValidatesOnExceptions="True">
  <Binding.ValidationRules>
    <localValidation:RequiredFieldRule />
</Binding.ValidationRules>
</Binding>
</TextBox>

I have the following example and so I loaded it up and tested what you are doing and I got the same problem. http://www.wpfsharp.com/2012/02/03/how-to-disable-a-button-on-textbox-validationerrors-in-wpf/

To prove that my suggestion works, I added the properties I mention to my example, and I added to my grid the bubbled event, Validation.Error="MainGrid_Error", and it fires.

Adding those properties causes the bubbled event to fire in my example.

Upvotes: 8

Related Questions