wpfvalidationbusiness-objects

Force validation on bound controls in WPF


I have a WPF dialog with a couple of textboxes on it. Textboxes are bound to my business object and have WPF validation rules attached.

The problem is that user can perfectly click 'OK' button and close the dialog, without actually entering the data into textboxes. Validation rules never fire, since user didn't even attempt entering the information into textboxes.

Is it possible to force validation checks and determine if some validation rules are broken?

I would be able to do it when user tries to close the dialog and prohibit him from doing it if any validation rules are broken.

Thank you.


Solution

  • We have this issue in our application as well. The validation only fires when bindings update, so you have to update them by hand. We do this in the Window's Loaded event:

    public void Window_Loaded(object sender, RoutedEventArgs e)
    {
        // we manually fire the bindings so we get the validation initially
        txtName.GetBindingExpression(TextBox.TextProperty).UpdateSource();
        txtCode.GetBindingExpression(TextBox.TextProperty).UpdateSource();
    }
    

    This will make the error template (red outline) appear, and set the Validation.HasError property, which we have triggering the OK button to disable:

    <Button x:Name="btnOK" Content="OK" IsDefault="True" Click="btnOK_Click">
        <Button.Style>
            <Style TargetType="{x:Type Button}">
                <Setter Property="IsEnabled" Value="false" />
                <Style.Triggers>
                    <!-- Require the controls to be valid in order to press OK -->
                    <MultiDataTrigger>
                        <MultiDataTrigger.Conditions>
                            <Condition Binding="{Binding ElementName=txtName, Path=(Validation.HasError)}" Value="false" />
                            <Condition Binding="{Binding ElementName=txtCode, Path=(Validation.HasError)}" Value="false" />
                        </MultiDataTrigger.Conditions>
                        <Setter Property="IsEnabled" Value="true" />
                    </MultiDataTrigger>
                </Style.Triggers>
            </Style>
        </Button.Style>
    </Button>