WPF DataGrid validation errors not clearing

s73v3r picture s73v3r · Feb 24, 2011 · Viewed 13.6k times · Source

So I have a WPF DataGrid, which is bound to an ObservableCollection. The collection has validation on its members, through IDataErrorInfo. If I edit a cell in a way so as to be invalid, and then tab away from it before hitting enter, then come back and make it valid, the cell will stop showing invalid, however, the "!" at the head of the row will still be there, and the ToolTip will reference the previous, invalid value.

Answer

Fredrik Hedblad picture Fredrik Hedblad · Sep 17, 2011

Not using Mode=TwoWay for DataGridTextColumns solves one version of the problem, however it seems that this problem can appear out of nowhere for other reasons as well.

(Anyone who has a good explanation as of why not using Mode=TwoWay solves this in the first place is probably close to a solution to this problem)

The same thing just happened to me with a DataGridComboBoxColumn so I tried to dig a little deeper.

The problem isn't the Binding in the Control that displays the ErrorTemplate inside DataGridHeaderBorder. It is binding its Visibility to Validation.HasError for the ancestor DataGridRow (exactly as it should be doing) and that part is working.

Visibility="{Binding (Validation.HasError),
                     Converter={StaticResource bool2VisibilityConverter},
                     RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}}}"/>

The problem is that the validation error isn't cleared from the DataGridRow once it is resolved. In my version of the problem, the DataGridRow started out with 0 errors. When I entered an invalid value it got 1 error so, so far so good. But when I resolved the error it jumped up to 3 errors, all of which were the same.

Here I tried to resolve it with a DataTrigger that set the ValidationErrorTemplate to {x:Null} if Validation.Errors.Count wasn't 1. It worked great for the first iteration but once I cleared the error for the second time it was back. It didn't have 3 errors anymore, it had 7! After a couple of more iterations it was above 10.

I also tried to clear the errors manually by doing UpdateSource and UpdateTarget on the BindingExpressions but no dice. Validation.ClearInvalid didn't have any effect either. And looking through the source code in the Toolkit didn't get me anywhere :)

So I don't have any good solutions to this but I thought I should post my findings anyway..

My only "workaround" so far is to just hide the ErrorTemplate in the DataGridRowHeader

<DataGrid ...>
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Setter Property="ValidationErrorTemplate" Value="{x:Null}"/>
        </Style>
    </DataGrid.RowStyle>
    <!-- ... -->
</DataGrid>