Search code examples
c#wpfwpfdatagrid

Remove ErrorTemplate from DataGridTemplateColumn ContentPresenter


I find that the ContentPresenter used to display the content of a DataGridTemplateColumn displays the default ErrorTemplate when the row's item contains validation errors. I can't see any direct way to prevent this. Any ideas?

Here is my first attempt to ensure there is no validation error template displayed:

<DataGridTemplateColumn Width="70" Header="Enabled" Validation.ErrorTemplate="{x:Null}" >
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <CheckBox IsChecked="{Binding Enabled.Value}"
                      HorizontalAlignment="Center"
                      VerticalAlignment="Center" Validation.ErrorTemplate="{x:Null}"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
    <DataGridTemplateColumn.CellStyle>
        <Style >
            <Setter Property="Validation.ErrorTemplate" Value="{x:Null}"/>
        </Style>
    </DataGridTemplateColumn.CellStyle>
</DataGridTemplateColumn>

Example

Using Snoop I see that the cell contains a ContentPresenter that is displaying the validation error.

I find I can disable this only by removing the error template on all content presenters in the data grid as such:

<DataGrid.Resources>
    <Style TargetType="ContentPresenter">
        <Setter Property="Validation.ErrorTemplate" Value="{x:Null}"/>
    </Style>
</DataGrid.Resources>

Is there a way to this that only affects the single DataGridTemplateColumn?

This post seems similar: DataGridCell Validation.ErrorTemplate ignored


Solution

  • I found a solution. Adding a resource style that targets the ContentPresenter from within the DataGridTemplateColumn.CellStyle solves the problem.

    <DataGridTemplateColumn.CellStyle>
        <Style TargetType="{x:Type DataGridCell}">
            <Style.Resources>
                <Style TargetType="{x:Type ContentPresenter}">
                    <Setter Property="Validation.ErrorTemplate" Value="{x:Null}"/>
                </Style>
            </Style.Resources>
        </Style>
    </DataGridTemplateColumn.CellStyle>