2016-09-17 3 views
0

DataGridの行の背景を設定したいと考えています。C#でDataGridを正しくトラバースする方法は?

私が最初に考えたのは、これを行うことでした。

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

は今、これは動作しますが、それは、データグリッド内のすべての行の背景を設定します。 私の次の思考はこれを実行することでした。

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

しかしこれは、行背景のいずれかが変更されることはありませんので、私は、私は根本的に間違って何かをやっていると仮定します。データグリッドの行を正しくトラバースして背景を設定するにはどうすればよいですか?あなたの質問がWPFタグ付けされている

+0

質問のタイトルと質問の要件doesntのマッチ。 – AnjumSKhan

答えて

0

リサイズが答える、これは...

DataGridViewの行は、行テンプレート(DataGridViewCellStyleクラス)でスタイリングされています。

以下は、グリッドに行を追加するためのスティップスチットスニペットコードグループです。 theGridは、行を追加するコントロールです。イベントは、dbから返された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にする必要があります。

RowStyleTrigger/DataTriggerを入力してください。

プログラムで、あなたが使用してItemに基づいDataGridRowを取得することができます:

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; 
     } 
    } 
関連する問題