如何在WPF中单独更改ListView列(每行的每个单元格)的颜色?
我有一个定期更新并显示一些分析数据的 ListView。
每行代表不同的源,列显示其分析值。
我想要的是仅在满足特定条件时更改单个单元格的背景颜色或字体颜色。
例如,如果“价格”列值变得小于 X,它将变为红色背景或字体。
但我不希望整行改变颜色,而只改变该行的“价格”列。
我知道如何更改整行的颜色,这里也有很多这样的例子,例如使用绑定。但我想知道是否有办法只更改单个单元格的背景颜色或字体颜色。
谢谢。
编辑:
感谢 Sean Manton 的回复,我很轻松地解决了这个问题。令人惊讶的是,我在搜索中找不到任何结果时遇到了很多问题,因此我还添加了自己的答案和一个工作示例。
I have a ListView that regularly update and show some analyzed data.
Each row represent a different source and the columns show it's analyzed values.
What I want is to only change the Background color or Font Color of a single cell if a certain criteria is met.
For example if the "Price" Column value become less than X, it will change into Red Color background or font.
But I don't want the whole row to be changing color, but only the "Price" Column of that certain row.
I know how to change the color of a whole row, there has been many example of that in here as well, for example using binding. But I want to know if there is anyway to just change the Background Color or Font Color of a single Cell.
Thanks.
Edit:
Thanks to Sean Manton's Reply, I solved this problem pretty easily. It's surprising that I had so much problem finding any result in my searches for this, so I added my own answer with a working example as well.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在搜索 CellTemplate 用法后,我很容易解决了问题,感谢 Sean Manton 的回复。
不知道为什么当我搜索 ListView 列或单元格的更改颜色时很难找到它,结果只显示“行”而不是“列”。
另外,这里的大多数答案总是使用绑定转换器,这似乎是更好的方法,但我注意到即使没有任何转换器并且使用非常简单的代码,这也可以工作。
因此,我将在这里编写这个示例,以防有人觉得它有用:
XAML 设计:
对于 C# 代码,我们只需制作一个列表,其中也包含“Price_Color”字符串值。
现在我们可以非常轻松地添加和自定义具有所需颜色的项目,如下所示:
现在我们的 ListView 中将有 3 行,每行仅针对“价格”列具有不同的字体颜色。
I solved the problem pretty easily after I search for the CellTemplate usage, Thanks to Sean Manton's reply.
Not sure why it was so hard for me to find this when I searched for changing color of ListView Column or Cell and the result only showed it for "Row" and not "Column".
Also, Most of the answers here always use a Binding Converter, which seems to be the better way to do it, But I noticed this can work even without any converter and with a very simple code as well.
So I will write this example here in case anyone find it useful:
XAML Design:
As for the C# Code, We just have to make a list which include the "Price_Color" string value as well.
And now we can very easily add and customize the items with our desired color like this :
Now we will have 3 row in our ListView each one having a different font color for the "Price" Column only.
GridViewColumn
有一个CellTemplate
属性,您可以将其指向单元格的DataTemplate
。在DataTemplate
中,您可以使用绑定转换器将值映射到所需的样式。GridViewColumn
has aCellTemplate
property that you can point to aDataTemplate
for the cells. In theDataTemplate
you can use a Binding Converter to map the values to the desired styling.