基于 DataGridCell 值的触发器
我在数据网格中有一些单元格,当某些列的值为 0 时,我想将某些列中的单元格突出显示为红色。我不知道如何解决这个问题。
我看过这个问题: WPF:如何突出显示符合条件的 DataGrid 的所有单元格? 但没有一个解决方案对我有用。
通过使用样式触发器,触发器似乎应该应用于属性。当我做某事时,什么也没有发生(我假设是因为内容比简单的值更多)。
通过最后建议的解决方案,我遇到了一个编译时问题,这似乎是 VS 中已经存在一段时间的错误的表现:自定义绑定类无法正常工作
我有什么想法可以实现这一点吗?
有人有什么想法吗?
I have some cells in a datagrid and I would like to highlight cells in certain columns red when their value is 0. I'm not sure how to approach this.
I've looked at this question: WPF: How to highlight all the cells of a DataGrid meeting a condition? but none of the solutions have worked for me.
With using style triggers, it seems that the triggers are meant to be applied on properties. When I do something like nothing happens (I'm assuming because there's more to the content than a simple value).
With the last suggested solution I was getting a compile-time issue which seemed to be a manifestation of a bug that's been in VS for a while now: Custom binding class is not working correctly
Any ideas how I can achieve this?
Anyone have any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据 DataGridCell 的值更改单元格背景颜色的最佳方法是使用转换器为 DataGridTemplateColumn 定义 DataTemplate 来更改单元格的背景颜色。此处提供的示例使用 MVVM。
以下示例中要搜索的关键部分包括:
1:将模型中的整数(Factor)转换为颜色的 XAML:
2:根据模型中的整数属性返回 SolidColorBrush 的转换器:
3:更改的 ViewModel模型中介于 0 和 1 之间的整数值,通过单击按钮来触发更改转换器中颜色的事件。
4:模型实现 INotifyPropertyChanged 用于通过调用 OnPropertyChanged 来触发事件以更改背景颜色
我已在答案中提供了此处所需的所有位,但用作的核心部分除外
MVVM 模式的基础,包括 ViewModelBase (INotifyPropertyChanged) 和 DelegateCommand,您可以通过 google 找到它们。请注意,我在代码隐藏的构造函数中将视图的 DataContext 绑定到 ViewModel。如果需要的话我可以发布这些额外的内容。
这是 XAML:
这是转换器:
这是 ViewModel:
这是模型:
The best way to change the background color of a cell based on the value of a DataGridCell is to define a DataTemplate for the DataGridTemplateColumn with a Converter to alter the Background color of the cell. The sample provided here uses MVVM.
The keys parts to search for in the following example include:
1: XAML that converts an integer (Factor) in the model to a color:
2: Converter that returns a SolidColorBrush based on an integer property in the model:
3: ViewModel that changes the integer value in the Model between 0 and 1 from a Button click to fire an event that changes the color in the Converter.
4: Model implements INotifyPropertyChanged used to fire the event to alter the background color by calling OnPropertyChanged
I've provided all bits needed here in my answer with the exception of core parts used as
the foundation of the MVVM pattern that includes ViewModelBase (INotifyPropertyChanged) and DelegateCommand which you can find in via google. Note that I bind the DataContext of the View to the ViewModel in the code-behind's constructor. I can post these additional bits if needed.
Here is the XAML:
Here is the Converter:
Here is the ViewModel:
Here is the Model: