views:

27

answers:

1

I have copied an example from MSDN and added the Validation.Error event. Problem is, it never gets fired. Why not?

<UserControl x:Class="MeasurementControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:src="clr-namespace:Controls"
         mc:Ignorable="d" 
         d:DesignWidth="300">

<StackPanel Margin="20">
    <StackPanel.Resources>
        <src:PersonImplementsIDataErrorInfo x:Key="data"/>

        <!--The tool tip for the TextBox to display the validation error message.-->
        <Style x:Key="textBoxInError" TargetType="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>

    </StackPanel.Resources>
    <TextBlock>Enter your age:</TextBlock>
    <TextBox Style="{StaticResource textBoxInError}" Validation.Error="TextBoxScalar_Error">
        <TextBox.Text>
            <!--ValidatesOnDataErrors to is set to True, so the Binding
      checks for errors raised by the IDataErrorInfo object.
      An alternative syntax is to add <DataErrorValidationRule/> within
      the <Binding.ValidationRules> section.-->
            <Binding 
                Path="Age" 
                Source="{StaticResource data}"
                ValidatesOnDataErrors="True"
                UpdateSourceTrigger="PropertyChanged">
            </Binding>
        </TextBox.Text>
    </TextBox>
    <TextBlock>Mouse-over to see the validation error message.</TextBlock>
</StackPanel>

+1  A: 

From the documentation of Validation.Error:

Occurs when the bound element runs into a validation error, but only for bindings with the NotifyOnValidationError value set to true.

You just need to set NotifyOnValidationError in your binding:

<Binding 
    Path="Age" 
    Source="{StaticResource data}"
    ValidatesOnDataErrors="True"
    UpdateSourceTrigger="PropertyChanged"
    NotifyOnValidationError="True">
</Binding>
Quartermeister