我有一个WPF DataGrid,它显示实现IDataErrorInfo的类型.正如预期的那样,当验证失败时,行会获得红色感叹号,无效的单元格将获得红色突出显示.

这一切都很好; 但是,我希望验证错误消息显示在无效单元格的工具提示中,以便用户有一些错误的指示.我现在有:
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="ToolTip"
Value="{Binding RelativeSource={RelativeSource Self},
Path=(Validation.Errors[0].ErrorContent}"/>
</Style>
</DataGrid.CellStyle>
Run Code Online (Sandbox Code Playgroud)
这种方法适用TextBox但不适用DataGridCell.有什么不同?
我现在正在进行的项目中有类似的东西,它是这样的:
<DataGridTextColumn.ElementStyle>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="DataGridCell.ToolTip"
Value="{Binding RelativeSource={RelativeSource Self},
Path=(Validation.Errors)[0].ErrorContent}"/>
</Style>
</DataGridTextColumn.ElementStyle>
Run Code Online (Sandbox Code Playgroud)
看看这个 MSDN 日志帖子:
https://blogs.msdn.microsoft.com/bethmassi/2008/06/27/displaying-data-validation-messages-in-wpf/
按照其说明创建一个文本框单元格编辑模板,该模板将如下所示:
<Style TargetType="TextBox" x:Key="errTemplate">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip"
Value="{Binding RelativeSource={x:Static RelativeSource.Self},
Path=(Validation.Errors)[0].ErrorContent}"/>
</Trigger>
</Style.Triggers>
</Style>
Run Code Online (Sandbox Code Playgroud)
然后,您可以通过像这样设置 EditingElementStyle 在您的数据网格中使用它:
<DataGridTextColumn Header="Variable"
Binding="{Binding Variable, ValidatesOnDataErrors=True}"
EditingElementStyle="{StaticResource errTemplate}"/>
Run Code Online (Sandbox Code Playgroud)
使用数据触发器很重要,这样您就可以支持标准工具提示以及出现错误时的工具提示,如本文所述:
| 归档时间: |
|
| 查看次数: |
6341 次 |
| 最近记录: |