title: How to get row index using DataGridCell object
body: <p>I am trying to retrieve the row index of the current DataGridCell object. I need it to change the background color of the cell if it is a diagonal cell.</p>
  
  <p>I tried two options as shown below, both options are giving me row index. But when I try to move the scroll bar (when grid is big) and come back to the top of datagrid the row index by both of these options give different row index every time for the same rows. Essentially, I get differently colored grid everytime I scroll down and up.</p>
  
  <pre><code>class CellFormatConverter : IValueConverter
  {
          public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
          {
              DataGridCell dgc = (DataGridCell)value;
              DataRowView rowView = (DataRowView)dgc.DataContext;
  
              //Option 1
              DependencyObject row = value as DependencyObject;
  
              while (row != null &amp;&amp; !(row is DataGridRow))
              {
                  row = VisualTreeHelper.GetParent(row);
              }
              int rowIndex = 0;
              if(row!=null)
              {
                  DataGridRow gridrow = (DataGridRow)row;
                  rowIndex = gridrow.GetIndex();
              }
  
              //option 2
              //int rowIndex = rowView.Row.Table.Rows.IndexOf(rowView.Row);
  
              if (dgc.Column.DisplayIndex == rowIndex)
              { 
              return Brushes.Red;
              } 
         return Brushes.White;
        }
   }
  </code></pre>
  
  <p>Update:
  After struggling with the problem, I figured that displayIndex for column keep changing that leads to this problem.
  Later, I removed displayIndex based implementation and now I am using the content value to decide the background color. Now, my problem is everytime I scroll down and scroll up the grid looks differently colored!!</p>