【问题标题】:How do I get WPF DataGrid bespoke error styling to work for value converter errors?如何让 WPF DataGrid 定制错误样式适用于值转换器错误?
【发布时间】:2020-07-19 19:02:42
【问题描述】:

上下文

我需要允许从视图模型显示和编辑日期时间日期的 WPF MVVM 应用程序。有些日期是“独立的”,有些日期在 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>

问题

将此应用于“独立”日期一切正常,例如

<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 日期错误格式的行为与我的独立日期相同?

【问题讨论】:

    标签: c# wpf validation datagrid formatting


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-08
      • 1970-01-01
      • 2013-07-24
      • 2015-07-25
      • 1970-01-01
      • 1970-01-01
      • 2011-09-18
      相关资源
      最近更新 更多