[英]WPF individual cell colors in DataGrid using DataTable
I have a DataGrid in WPF. 我在WPF中有一个DataGrid。 The DataGrid is bound to data in a DataTable.
DataGrid绑定到DataTable中的数据。 The DataGrid has ItemsSource="{Binding}".
DataGrid具有ItemsSource =“{Binding}”。 There are no set DataGridTextColumn entries.
没有设置DataGridTextColumn条目。 The DataTable columns/rows are determined dynamically through database tables.
DataTable列/行是通过数据库表动态确定的。
In the example below the database column names are put into a list and the DataTable is setup so there is a name in the first column and a series of integer values following: 在下面的示例中,数据库列名称被放入列表中,并且设置了DataTable,因此第一列中有一个名称,下面是一系列整数值:
DataTable theDataTable= new DataTable();
theDataTable.Columns.Add("Name", typeof(string));
for(int i = 0; i < columnNameList.Count ; i++)
theDataTable.Columns.Add(columnNameList[i], typeof(int));
Next the DataGrid is associated (bound) to the DataTable 接下来,DataGrid与DataTable相关联(绑定)
theDataGrid.DataContext = theDataTable;
Next the rows are setup in the DataTable. 接下来,在DataTable中设置行。 Again, the number of rows is determined by users in the database.
同样,行数由数据库中的用户确定。 User names are put into a list after a database call.
数据库调用后,用户名将放入列表中。 Row values are defaulted to zero.
行值默认为零。
for (int i = 0; i < usersNames.Count ; i++)
{
DataRow newDataRow = theTradersDataTable.NewRow();
newDataRow["Name"] = usersNames[i];
for(int j = 0; i < columnNameList.Count ; j++)
{
newDataRow[columnNameList[j]] = 0;
}
theDataTable.Rows.Add(newDataRow);
}
Following the DataGrid setup, I connect to an API that provides callbacks with user information updates. 在DataGrid设置之后,我连接到一个API,该API提供带有用户信息更新的回调。 Upon the update, I determine the row and column that should be update the underlying DataTable which in turn updates the DataGrid.
在更新时,我确定应该更新基础DataTable的行和列,然后更新DataGrid。 This all works just fine.
这一切都很好。
//inside some API callback
theDataTable.Rows[rowNumber][columnNumber] = someDataSentInViaAPI;
Finally the question: How do you update a particular cell's color of the DataGrid based on the value in that cell. 最后一个问题:如何根据该单元格中的值更新DataGrid的特定单元格颜色。 Upon callbacks from the API where I receive the data, the cells are updating continuously.
在从我接收数据的API回调时,单元格不断更新。 So I'd like to update the color of the cell as the updates come in.
所以我想在更新进来时更新单元格的颜色。
I am not married to my design. 我没和我的设计结婚。 I do not want to make this model fit based on code I've already done.
我不想根据我已经完成的代码使这个模型适合。 I am up for most any idea but I would prefer not to hard code column names.
我对任何想法都很满意,但我不想硬编码列名。 I would also prefer a method that allows me to check a cell's color and then only repaint if necessary (for speed/CPU reasons).
我也更喜欢一种方法,它允许我检查单元格的颜色,然后只在必要时重新绘制(出于速度/ CPU的原因)。 Thank you in advance for all help.
提前感谢您的帮助。
Look into data triggers. 查看数据触发器。 The following Stack Overflow question can give you an example.
以下Stack Overflow问题可以为您提供示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.