wpftextbox.net-4.5validationrule

WPF 4.5 empty TextBox validation on startup


I have a simple textbox with a validation rule, but a very weird behavior in a special situation.

If I use my code as this, and that my property is 0 (as it comes from db), it works as expected. The TextBox gets its red border at start.

<TextBox x:Name="TxtOfferNumber"
        IsReadOnly="{Binding SelectedOffer.IsValid}"
        GotKeyboardFocus="TxtOfferNumber_GotKeyboardFocus"
        GotMouseCapture="TxtOfferNumber_GotMouseCapture">
    <TextBox.Text>
        <Binding Path="OfferNumberLookup" UpdateSourceTrigger="PropertyChanged">
            <Binding.ValidationRules>
                <validators:OfferNumberValidator ValidatesOnTargetUpdated="True"/>
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>

My validation rule:

   public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        return string.IsNullOrWhiteSpace(value as string) || Convert.ToInt32(value) != 0 ?
            ValidationResult.ValidResult :
            new ValidationResult(false, "Le numéro d'offre doit être informé!");
    }

The problem is that I want this field as required, so empty is not valid.

As I want my validation rule to be:

   public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        return !string.IsNullOrWhiteSpace(value as string) && Convert.ToInt32(value) != 0 ?
            ValidationResult.ValidResult :
            new ValidationResult(false, "Le numéro d'offre doit être informé!");
    }

And there is my big headache. The validation function returns correct result, but no red border. If I enter correct value and change to wrong value (empty or 0), now I get the red border.


Solution

  • If the problem is that the TextBox does not become validated on start-up, only when the input changes, a quick and dirty fix could be to set the Text (or binding property) to something correct and then something false during load.