需要根据数据绑定的值来设置行的背景色

动态 未结 0 67
小小草
小小草 LV1 2023年9月23日 23:40 发表
如果需要根据数据绑定的值来设置行的背景色,可以在 MyData 类中添加一个属性来表示行的颜色,然后在 DataGridView 的 CellFormatting 事件中根据该属性来设置单元格的背景色。例如,下面的代码将 Age 大于 30 的行的背景色设置为红色: ```csharp public class MyData : INotifyPropertyChanged { private string _name; private int _age; private Color _rowColor; public string Name { get { return _name; } set { if (_name != value) { _name = value; OnPropertyChanged("Name"); } } } public int Age { get { return _age; } set { if (_age != value) { _age = value; OnPropertyChanged("Age"); // 根据年龄设置行颜色 RowColor = _age > 30 ? Color.Red : Color.White; } } } public Color RowColor { get { return _rowColor; } set { if (_rowColor != value) { _rowColor = value; OnPropertyChanged("RowColor"); } } } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } ``` 在 Form_Load 事件中,我们可以创建 MyData 对象的列表作为数据源,并将其绑定到 DataGridView 控件上。接着,我们可以通过设置 DefaultCellStyle 和 AlternatingRowsDefaultCellStyle 属性来分别设置奇数行和偶数行的背景色,并在 CellFormatting 事件中根据 MyData 对象的 RowColor 属性来设置单元格的背景色。 ```csharp private void Form1_Load(object sender, EventArgs e) { // 创建数据源 List myDataList = new List(); myDataList.Add(new MyData { Name = "Alice", Age = 25 }); myDataList.Add(new MyData { Name = "Bob", Age = 30 }); myData
收藏(0)  分享
相关标签: 智能问答
问题没解决?让AI助手帮你作答 AI助手
0个回复
  • 消灭零回复