title: Looping Through WPF DataGrid Using foreach
body: <p>All, I am attempting to loop through a WPF <code>DataGrid</code> using a for each loop to change the background colour of erroneous cells. I have checked many questions but I have yet to find a sufficient answer. What I have so far is </p>
  
  <pre><code>public void RunChecks()
  {
      const int baseColumnCount = 3;
      foreach (DataRowView rv in dataGrid.Items)
      {
          for (int i = baseColumnCount; i &lt; dataGrid.Columns.Count; i++)
          {
              if (!CheckForBalancedParentheses(rv.Row[i].ToString()))
              {
                  Color color = (Color)ColorConverter.ConvertFromString("#FF0000");
                  row.Background = new SolidColorBrush(color); // Problem!
              }
          }
      }
  }
  </code></pre>
  
  <p>The problem is that in order to change the <code>Background</code> colour of a row in my <code>DataGrid</code> I need to work with the <code>DataGridRow</code> object ascociated with the <code>DataRowView</code> <code>rv</code>. </p>
  
  <p><strong>How do I get a reference to the <code>DataGridRow</code> from the object <code>rv</code> (<code>DataRowView</code>)?</strong></p>
  
  <p>Thanks for your time.</p>
  
  <p><em>Edit. Based upon the advice below I now have the following style which works with the mouse over event and set the back and fore font of the relevant cell. However, I am really lost as to how to apply the backcolor to a cell at run-time in my code above. The XML style is</em></p>
  
  <pre><code>&lt;Window.Resources&gt;
      &lt;Style TargetType="{x:Type DataGridRow}"&gt;
          &lt;Style.Triggers&gt;
              &lt;Trigger Property="IsMouseOver"
                       Value="True"&gt;
                  &lt;Setter Property="Background" Value="Red" /&gt;
                  &lt;Setter Property="FontWeight" Value="ExtraBold" /&gt;
              &lt;/Trigger&gt;
          &lt;/Style.Triggers&gt;
      &lt;/Style&gt;
  &lt;/Window.Resources&gt;
  </code></pre>