Search code examples
c#wpfvalidationrules

WPF validation error remains until control loses focus


I got a text box on which I added a validation rule in the xaml. The rule works and it detects errors, but only after the user gives the focus to some other element in the window, like another text box.

This is the defintion:

<TextBox x:Name="textBoxLongitude" Grid.Row="1" Grid.Column="1" Margin="0,0,0,10" VerticalContentAlignment="Center">
        <TextBox.Text>
            <Binding Path="CustomerLongitude">
                <Binding.ValidationRules>
                    <local:IsDoubleValidationRule MaxValue ="180"/>
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>
    </TextBox>

I've tried solving the issue by adding this to the xaml of the text box:

TextChanged="textBoxTextChanged"

And the implementation:

private void textBoxTextChanged(object sender, TextChangedEventArgs e)
{
     CommandManager.InvalidateRequerySuggested();
}

It didn't help..

How can I make the validation rule detect the error and when it's fixed even without the user needing to give the focus to another control?


Solution

  • Set the binding's UpdateSourceTrigger to PropertyChanged to commit and re-evaluate a bound value on every change instead of LostFocus.

    Bindings that are TwoWay or OneWayToSource listen for changes in the target property and propagate them back to the source. This is known as updating the source. Usually, these updates happen whenever the target property changes. This is fine for check boxes and other simple controls, but it is usually not appropriate for text fields. Updating after every keystroke can diminish performance and it denies the user the usual opportunity to backspace and fix typing errors before committing to the new value. Therefore, the default UpdateSourceTrigger value of the Text property is LostFocus and not PropertyChanged.

    This is how to do it: <Binding Path="CustomerLongitude" UpdateSourceTrigger="PropertyChanged">