Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Validation Result Popup

I'm trying to implement WPF validation on a few text boxes. I want to be able to display the validation errors to the user with something more obvious than a tool-tip, but more subtle than a dialog or messagebox. I settled on using the Popup class, rather than some built in textbox for displaying errors, since there are many different fields that need to be validated this way, and I want the feedback to be "attached" to the field in question.

The problem I'm experiencing is that the binding of the Popup's child TextBox to the attached TextBox's (Validation.Errors) property is not updated aggressively enough. As soon as there is an Error object, the text is updated and displayed (i.e. "Please enter a name." for an empty field) but if the error changes (i.e. the user enters invalid text) the message in the popup stays the same... until/unless they enter valid input, at which point the popup disappears as desired.

I've done some debugging, and I've found that while the validation rule is being called correctly and returning the proper results, the converter for the Popup is only called at the creation of the initial error. I guess what I am confused about is why the Popup gets updated only when the validation state goes from "no errors" to "some error(s)", so to speak. Does anyone know a way to force the changes to Validation.Errors to be reflected in my Popup's TextBox.Text?

Here's a xaml example of what I've written.

<TextBox Name="MyTextBox">
    <TextBox.Text>
        <Binding Path="MyText" UpdateSourceTrigger="PropertyChanged" >
            <Binding.ValidationRules>
                <local:MyTextBoxValidationRule />
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>
<Popup Name="MyPopup" IsOpen="{Binding ElementName=MyTextBox, 
    Path=(Validation.HasError), Mode=OneWay}">
    <Border BorderThickness="1" BorderBrush="Red" Background="White">
        <TextBlock Foreground="Red" Margin="5 5 5 5" 
            Text="{Binding ElementName=MyTextBox, Path=(Validation.Errors), 
            Converter={StaticResource errorsToMessageConverter}}"/>
    </Border>
</Popup>
like image 431
John Moran Avatar asked Dec 03 '25 06:12

John Moran


1 Answers

I was able to find a compromise. I changed the binding on the Popup's TextBlock like so:

<TextBlock Name="MyPopupTextBox" Foreground="Red" Margin="5 5 5 5" 
    Text="{Binding ElementName=MyTextBox, Path=(Validation.Errors)[0].ErrorContent, 
    UpdateSourceTrigger=PropertyChanged, Mode=OneWay, NotifyOnValidationError=True, 
    NotifyOnSourceUpdated=True, ValidatesOnExceptions=True}"/>
like image 171
John Moran Avatar answered Dec 06 '25 06:12

John Moran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!