2016-09-17 23 views
0

我想能夠設置DataGrid的行的背景。如何正確遍歷C#中的DataGrid?

我首先想到的是要做到這一點:

//MapDisplay is a DataGrid 
SolidColorBrush myBrush = new SolidColorBrush(Colors.Red); 
mapDisplay.RowBackground = myBrush; 

現在,這個工作,但它會設置在DataGrid中每一行的背景。 我的下一個想法是要做到這一點:

SolidColorBrush myBrush = new SolidColorBrush(Colors.Red); 
foreach (DataGridRow x in mapDisplay.Items) 
{ 
    x.Background = myBrush; 
} 

然而,這不會導致任何行背景的變化,所以我認爲我在做某種根本性錯誤。如何正確遍歷DataGrid的行來設置背景?

+0

問題標題和問題要求犯規的比賽。 – AnjumSKhan

回答

0

你的問題被標記WPF,這是的WinForms回答...

DataGridView的行與列模板(的DataGridViewCellStyle類)風格。

下面是一組拼接在一起的代碼組,將行添加到網格中。 theGrid是我們要添加行的控件。事件是從數據庫返回的POCO。

   var rowCellStyle = new DataGridViewCellStyle(theMessagesGrid.DefaultCellStyle) 
       { 
        BackColor = string.IsNullOrEmpty(conditions) 
          ? theGrid.DefaultCellStyle.BackColor 
          : theColor, 
        SelectionForeColor = Color.WhiteSmoke, 
        SelectionBackColor = theGrid.DefaultCellStyle.SelectionBackColor, 
       }; 

      var theRow = new DataGridViewRow 
       { 
        Height = theGrid.RowTemplate.Height, 
        DefaultCellStyle = rowCellStyle, 
        Tag = Event.GroupName 
       }; 

      theRow.CreateCells(theGrid); 
      var cellData = new object[theRow.Cells.Count]; 

      // fill out cell data 
      cellData[0] = ...; 
      cellData[1] = ... 
      theRow.SetValues(cellData); 

      // add row to grid 
      try 
      { 
       theGrid.Rows.Add(theRow); 
       if (currentMsg == Event.Pkey) theGrid.Rows[theGrid.Rows.Count - 1].Selected = true; 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show(ex.Message, @"Error Building Grid", MessageBoxButtons.OK, MessageBoxIcon.Warning); 
       throw; 
      } 

WPF應該有某種形式適用於行。添加存儲行模板的表單屬性,然後根據條件更新rowCellStyle。

0

要更改特定行的背景,需要根據其DataContext或其index的某個值獲取該行。

然後將Trigger/DataTrigger應用於您的RowStyle

編程,您可以使用獲得基於ItemDataGridRow

DataGridRow row = (DataGridRow) mapDisplay.ItemContainerGenerator.ContainerFromItem(item); 

mapDisplay.Items會給你有限的項目可以是Map objects,或一般Employee對象列表。

ContainerFromIndex() method基於索引。

而現在,校正代碼,

foreach (object o in mapDisplay.Items) 
    { 
     Map m = o as Map; 
     if (m == null) break; 

     if (m.AreaCode == 1234) 
     { 
      DataGridRow row = (DataGridRow)mapDisplay.ItemContainerGenerator.ContainerFromItem(m); 
      row.Background = Brushes.Yellow; 
     } 
    }