DEV Community

Cover image for Why WPF Validation Errors Are Not Displayed, and Choosing Between IDataErrorInfo and INotifyDataErrorInfo
s-iguchi09
s-iguchi09

Posted on Edited on Originally published at s-iguchi09.github.io AI-assisted

Why WPF Validation Errors Are Not Displayed, and Choosing Between IDataErrorInfo and INotifyDataErrorInfo

The required-field check is written, but the TextBox never turns red. Sometimes the check never runs at all. Sometimes it runs, Validation.GetHasError is true, and the screen still shows nothing.

This is a short summary. The full article, with measurements for each case on .NET 10, is here:
Why WPF Validation Errors Are Not Displayed, and Choosing Between IDataErrorInfo and INotifyDataErrorInfo

Start from Validation.GetHasError

  • false: no rule is attached, or the input has not reached the source yet. IDataErrorInfo does nothing until the binding has ValidatesOnDataErrors="True", because that setting is false by default. INotifyDataErrorInfo is the only approach that is on by default. Typed text is checked only when it reaches the source, which for TextBox.Text happens on focus loss.
  • true, but nothing on screen: the error template has nowhere to draw. A replaced Window template without an AdornerDecorator leaves no adorner layer. Inside a ScrollViewer the layer still exists, so only some fields go silent.
  • A red border with no message: this is just how the default ErrorTemplate works. It never shows the text.

The fix for the message

Supply your own template:

<ControlTemplate x:Key="FieldErrorTemplate">
    <StackPanel>
        <Border BorderBrush="#D13438" BorderThickness="1">
            <AdornedElementPlaceholder x:Name="Adorned" />
        </Border>
        <TextBlock Foreground="#D13438"
                   Text="{Binding ElementName=Adorned,
                          Path=AdornedElement.(Validation.Errors)/ErrorContent}" />
    </StackPanel>
</ControlTemplate>
Enter fullscreen mode Exit fullscreen mode

Adorners take no layout space, so reserve a bottom margin. For new code where the view model owns validation, the article recommends INotifyDataErrorInfo, and remember to raise ErrorsChanged when an error clears.

A Japanese version is also available.

Related Articles

Top comments (0)