具有验证错误样式的 WPF Datagrid 单元格
当出现验证错误时,我试图更改 DataGridCell(在 WPF 工具包 DataGrid 中)的默认样式。默认为红色边框。我怎样才能放置自己的模板?
谢谢。
I am trying to change the default style of a DataGridCell (within a WPF Toolkit DataGrid) when there is a validation error. The default is a red border. How can I put my own template?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
试试这个:
并使用它:
Try this:
And use it:
有一个不错的教程 来自 Diederik Krols 的内容完全符合您对 WPF Toolkit DataGrid 的要求。
There's a nice tutorial from Diederik Krols that does exactly what you're asking for the WPF Toolkit DataGrid.
下面是一种解决方案,但首先,让我分享我的发现。
验证错误似乎永远不会到达列的 ElementStyle 或 CellStyle 内部。我怀疑这是因为它达到并可以在列的 EditingElementStyle 和数据网格的 RowStyle 中使用。
例如,您可以根据 Validation.HasError: 设置样式,
或者也可以设置 Validation.ErrorTemplate: ,
两者都可以正常工作。在 EditingElementStyle 上也是如此。这些都没有真正解决问题:更改行样式显然不会显示错误所在的单元格,并且一旦文本框散焦,编辑样式就不可见。
不幸的是,由于某种原因,相同的方法不适用于 ElementStyle 或 CellStyle。我倾向于相信这是一个错误,因为在 本教程在展示了在 EditingElementStyle 上设置 Validation.HasError 触发样式的示例后说道:
解决方案
一种解决方法是不使用触发器,而是将单元格的背景(或任何您想要的样式属性)绑定到数据对象的新属性。我会表明我的意思。
在此示例中,有一些产品,它们有一个类别,该类别将显示在数据网格中的文本列中。这是 XAML:
这是 Product 类:
显然,此解决方案的巨大缺点是它需要为数据对象中的每个属性提供一个(或多个,如果您想要更复杂的样式)样式属性,并且需要大量手动操作这些属性的设置。但这仍然是一种解决方案。
One kind of solution is below, but first, let me share my findings.
It seems like the validation errors never reach inside the column's ElementStyle or CellStyle. The reason I suspect this is because it reaches and can be used in the column's EditingElementStyle and the datagrid's RowStyle.
For example, you can set the style based on Validation.HasError:
or you can set the Validation.ErrorTemplate as well:
and both work just fine. Same on the EditingElementStyle. Neither of these really solves the problem: changing the row style obviously doesn't show which cell the error is in, and the editing style is not visible once the text box is defocused.
Unfortunately, for some reason, the same method doesn't work on the ElementStyle or the CellStyle. I'm inclined to believe this is a bug because in this tutorial it says after showing an example of setting a Validation.HasError triggered style on the EditingElementStyle:
The solution
One workaround is not to use a trigger but rather bind the background (or whatever style property you want) of the cell to a new property of the data object. I'll show what I mean.
In this example, there are products, they have a category, which will be displayed in a text column in the datagrid. Here's the XAML:
And here's the Product class:
Obviously, the huge downside of this solution is that it requires one (or more if you want more complex styles) style property for every property in the data object, and it needs a lot of manual settings of these properties. But it is kind of a solution nevertheless.