如何根据 DataGrid 中的值以编程方式(WPF 和 C#)设置 WPF DataGrid 的行背景颜色
我有一个与接口对象列表绑定的 WPF Datagrid。 考虑一下,ClsEmployee 类实现了 I_Employee 接口,其中包含 Empl_Id、Empl_Name、Department、Address 和 City_name 属性。
列表_emplList;
考虑一下,_emplList 有 10 个项目。
dgEmployeeGrid.ItemsSource = _emplList;
问题: 现在,如果用户单击按钮,那么我应该能够读取 City_name。基于 City_name,我应该能够通过 C# 代码动态设置行的颜色(每行的颜色可以不同)。
请帮助我该怎么做?
提前致谢!
I have a WPF Datagrid binded with list of interface objects.
Consider, ClsEmployee class implements I_Employee interface with properties Empl_Id, Empl_Name, Department, Address and City_name.
List _emplList;
consider, _emplList has 10 items.
dgEmployeeGrid.ItemsSource = _emplList;
Question:
Now, if the user clicks on a button, then i should be able to read the City_name. Based on the City_name, i should be able to set the color (Color can be different for each row) for the rows dynamically through C# code.
Please help me how to do this?
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
构建一个 ValueConverter ,它接受“网格中适当类型的值”,然后使用 ValueConverter 将行的背景颜色绑定到该字段,以提供 颜色画笔 或您想要放入其中的任何其他类型的画笔(有意义)。
编辑
这是一个将布尔颜色转换为画笔颜色的转换器。这个类有两个属性,称为“True”和“False”,我们设置一个 Brush,当布尔值与属性匹配时将使用它们。转换器是一种方法,不会将画笔转换回布尔值。
用于创建转换器实例并设置属性的 XAML
C# 转换器代码
绑定值并转换为采用画笔的对象上的字段的示例
I假设您熟悉 WPF 中的数据绑定,并且不会详细说明解决方案的这方面,但是当
Reviewer.IsMentor
为 true 时,转换器将提供“绿色”画笔(当转换器创建)到椭圆的 Fill 属性。Build a ValueConverter that takes in a "value" of the appropriate type in the grid, and then bind the Background color of the row to that field with the ValueConverter in there to provide the Color brush or whatever other kind of brush (that makes sense) that you'd like to put in there.
EDIT
Here is a Converter that converts a bool to a Brush color. This class has two properties called "True" and "False" which we set a Brush to that will be used when the boolean value matches the property. The converter is one way and does not convert brushes back to boolean values.
XAML to create instance of the Converter and set properties
C# Converter Code
Example of binding value and convert to a field on an object that takes brushes
I'm assuming you are familiar with databinding in WPF and won't elaborate that aspect of the solution but when the
Reviewer.IsMentor
is true, the Converter will provide a "Green" brush (sent when the Converter was created) to the Fill property of the ellipse.