基于单元格值的DataGrid行背景

我目前正在开发一个C#WPF数据网格。 我有一个DataGrid,它有自动生成的列,代码连接到SQLite数据库并创建数据集,然后将此数据集设置为DataGrid ItemsSource。

下面是DataGrid的XAML代码

  

以下是为DataGrid设置ItemsSource的代码

 try { DataSet ds = new DataSet(); SQLiteDataAdapter da = new SQLiteDataAdapter(query, db.conn); da.Fill(ds); //tblGrid.AutoGenerateColumns = true; tblGrid.ItemsSource = ds.Tables[0].DefaultView; } catch (SQLiteException ex) { MessageBox.Show("Unable to retrieve logins from database.\n\n" + ex.Message + "\n\nError Code: " + ex.ErrorCode); } 

数据库中显示的列(自动生成)是ID,日期,时间,状态。 我需要做的是,如果状态列的行中的值等于错误,则更改该行的背景颜色。

我假设我需要在DataGrid标签中添加某种样式标签和DataTriggers,但不确定我需要什么。 我尝试过设置ItemsSource的代码的任何内容都会显示一条错误,指出在添加ItemsSource之前Source必须为空。

感谢您的任何帮助,您可以提供。

您可以使用DataTrigger执行此操作。

这是一个快速的样本。 我创建了一个名为Person的类,其属性为Name,Age和Active。

 public class Person { public string Name { get; set; } public int Age { get; set; } public bool Active { get; set; } } 

在主窗口的构造函数中,我将3个Person对象添加到列表中,然后将该列表绑定到DataGrid

 public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); List people = new List(); people.Add(new Person() { Name = "John Doe", Age = 32, Active = true }); people.Add(new Person() { Name = "Jane Doe", Age = 30, Active = true }); people.Add(new Person() { Name = "John Adams", Age = 64, Active = false }); tblLog.ItemsSource = people; } } 

然后在MainWindow的XAML中,我创建了一个DataTrigger样式作为资源。

    

此触发器的作用是从DataGridRow中的Person对象获取Active字段中的值,如果该值为false,则它将该行的背景颜色变为红色。