我有一个数据网格,我试图使用datagrid_LoadingRow事件处理程序更改单个行颜色。我遇到的问题是,它将数据网格中的每一行着色为相同的颜色,而不是每个单独的行,具体取决于满足的条件。
这是我的代码,如何将其应用于每个单独的行?
private void schDataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
{
foreach (DataRowView dr in schDataGrid.Items)
{
string DUEDATE = dr["DUEDATE"].ToString();
DateTime now = Convert.ToDateTime(DateTime.Now.ToString("dd/MM/yyyy"));
DateTime compareDate = Convert.ToDateTime(DUEDATE);
TimeSpan difference = now - compareDate;
if (difference.Days <= 0)
{
e.Row.Background = new SolidColorBrush(Colors.ForestGreen);
e.Row.Foreground = new SolidColorBrush(Colors.White);
}
else if (difference.Days > 0 && difference.Days <= 60)
{
e.Row.Background = new SolidColorBrush(Colors.Orange);
e.Row.Foreground = new SolidColorBrush(Colors.Black);
}
else if (difference.Days > 60)
{
e.Row.Background = new SolidColorBrush(Colors.Red);
e.Row.Foreground = new SolidColorBrush(Colors.White);
}
}
}
感谢您一如既往的帮助。
答案 0 :(得分:1)
为每一行调用函数schDataGrid_LoadingRow。 因此,不要循环所有项目,而是取出行的项目:
var dr = e.Row.Item as yourItem
// Other stuff....
if (difference.Days <= 0)
{
e.Row.Background = new SolidColorBrush(Colors.ForestGreen);
e.Row.Foreground = new SolidColorBrush(Colors.White);
}
else if (difference.Days > 0 && difference.Days <= 60)
{
e.Row.Background = new SolidColorBrush(Colors.Orange);
e.Row.Foreground = new SolidColorBrush(Colors.Black);
}
else if (difference.Days > 60)
{
e.Row.Background = new SolidColorBrush(Colors.Red);
e.Row.Foreground = new SolidColorBrush(Colors.White);
}