如何让 WPF DataGrid 定制错误样式适用于值转换器错误?

How do I get WPF DataGrid bespoke error styling to work for value converter errors?

上下文

WPF MVVM 应用程序,我需要允许从视图模型显示和编辑日期时间日期。有些日期是 "free standing",有些在 DataGrid 中。错误处理(范围检查等)是通过 INotifyDataErrorInfo 和验证服务进行的。我这样设置错误日期以突出显示它们并提供带有错误消息的工具提示:

<Style x:Key="ErrorStyle" TargetType="{x:Type Control}">
    <Style.Triggers>
        <Trigger Property="Validation.HasError" Value="true">
            <Setter Property="ToolTip">
                <Setter.Value>
                    <ToolTip DataContext="{Binding RelativeSource={RelativeSource Self}, Path=PlacementTarget}">
                        <ItemsControl ItemsSource="{Binding Path=(Validation.Errors)}" DisplayMemberPath="ErrorContent" />
                    </ToolTip>
                </Setter.Value>
            </Setter>
            <Setter Property="Background" Value="Salmon"/>
            <Setter Property="Height" Value="20"/>
        </Trigger>                
    </Style.Triggers>
</Style>

问题

将此应用于 "free standing" 日期一切正常,例如

<TextBox x:Name="dueDate"
         Style="{StaticResource ErrorStyle}"
         Text="{Binding Path=DueDate,
                        StringFormat=d, ConverterCulture={x:Static gl:CultureInfo.CurrentCulture},
                        ValidatesOnNotifyDataErrors=True}">
</TextBox>

当发生值转换器错误(例如无效的日期格式)或验证服务发现错误时,两者都有效。

但是对于 DataGrid 中的日期,情况有所不同:

<DataGridTemplateColumn Header="Delivery date" SortMemberPath="DeliveryDate">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBox Text="{Binding Path=DeliveryDate, StringFormat=d, ConverterCulture={x:Static gl:CultureInfo.CurrentCulture}}"
                     Style="{StaticResource ErrorStyle}"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
    <DataGridTemplateColumn.CellEditingTemplate>
        <DataTemplate>
            <TextBox Text="{Binding DeliveryDate, Mode=TwoWay, UpdateSourceTrigger=LostFocus,
                            StringFormat=d,
                            ConverterCulture={x:Static gl:CultureInfo.CurrentCulture},
                            ValidatesOnNotifyDataErrors=True}"/>                                               
        </DataTemplate>
    </DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>

此处我的样式适用于验证服务发现的错误。但是,对于值转换器错误,我得到一个红色环绕,没有工具提示,所有其他字段都被禁用。我收集到后者是此类错误的默认行为。

问题

如何让我的 DataGrid 日期错误格式设置与独立日期的行为方式相同?

终于解决了这个问题。我需要将我的 ErrorStyle 添加到 CellEditingTemplate 以及 CellTemplate。