wpf datagrid行颜色变化没有发生

时间:2014-08-14 13:45:34

标签: c# wpf datagrid

我正在将WPF Datagrid行项的行值与数据库项进行比较,找到匹配后我需要更改Datagrid中特定行的颜色。 找到匹配工作正常

  foreach (System.Data.DataRowView rowview in dataGrid1.Items )
  {
    var Srow = dataGrid1.ItemContainerGenerator.ContainerFromItem(dataGrid1.SelectedItem) as DataGridRow;
    Srow.Background = Brushes.LightGreen;
  }

给出错误(空引用未处理。)我尝试了所有选项保持索引,rowview.Row ["名称"] .....

欢迎任何建议。

1 个答案:

答案 0 :(得分:0)

您好我建议您实施 LoadingRow 事件,因为更改行样式会更容易:

  //The event: 
   dataGrid1.LoadingRow += new EventHandler<DataGridRowEventArgs>(dataGrid1_LoadingRow);

现在处理事件的函数

  //Here come the function
   private void dataGrid1_LoadingRow(object sender, DataGridRowEventArgs e)
   {
     //your test here to see if they match...
       DataRowView row = (DataRowView)e.Row.Item;
       String Content = row.Row[i].ToString();
       if(Content = //Did it matche something ?)
       { 
         //If yes:
          e.Row.Background = new SolidColorBrush(Color.FromArgb(255, 217, 77, 77));
         //or 
         e.Row.Background = Brushes.LightGreen;
       }
   } 

那就是它,让我知道它是否适合你。