WPF Validation not firing when first load

2019-05-29 00:59发布

问题:

In Prism application I want to using validation.And I have implement the INotifyDataError interface in my ViewModel ,but I found that the validate solution don't be fired when the control is loaded first time.

Then I found the same Question like 'wpf Validation Binding not fired on First Load'

I Found a solution to solve the problem WPF don't fired the validation when first load the datacontext is that:

<TextBox Grid.ColumnSpan="2" Grid.Row="1" x:Name="textBoxFolder" Margin="2,4">
    <TextBox.Text>
        <Binding Path="this.MovieFolder" UpdateSourceTrigger="PropertyChanged">
            <Binding.ValidationRules>
                <!--  Validation rule set to run when binding target is updated. -->
                <Rules:MandatoryInputRule ValidatesOnTargetUpdated="True" />
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>

as you see,ValidatesOnTargetUpdated="True" is the key point ,this property will make WPF fired the validation when the datacontext load first time.

But I think that's a ugly solution. I need to add a Binding.ValidationRules for every control I want to validate.

Is there a good way to solve the problem.

回答1:

OK I've solved it: You force the validation when the element got bound with a simple property - ValidatesOnTargetUpdated:

 <rules:MyValidationRule ValidatesOnTargetUpdated="True"  ValidationType="notnull"/>