Search code examples
c#wpfdatagridrowforeground

Datagrid row foreground colour change not working


this is the continuation to :

How to programmatically form an observable collection and bind it to a datagrid

so I build a datagrid through:

string[] columnLabels = new string[] { "Column 0", "Column 1", "Column 2", "Column 3", "Column 4", "Column 5" };

foreach (string label in columnLabels)
{
  DataGridTextColumn column = new DataGridTextColumn();
  column.Header = label;
  column.Binding = new Binding(label.Replace(' ', '_'));

  dtgResults.Columns.Add(column);
}

int[] ivalues = new int[] { 0, 1, 2, 3 };
string[] svalues = new string[] { "A", "B", "C", "D" };

dynamic row = new ExpandoObject();

for (int i = 0; i < 6; i++)
{

  switch (i)
  {
   case 0:
   case 1:
   case 2:
    string str = columnLabels[i].Replace(' ', '_');
    ((IDictionary<String, Object>)row)[str] = ivalues[i];
    break;

   case 3:
   case 4:
   case 5:
    string str2 = columnLabels[i].Replace(' ', '_');
    ((IDictionary<String, Object>)row)[str2] = svalues[i - 3];
  break;

  }
}
dtgResults.Items.Add(row);

so now I would like to be able to change foreground colour here not having to go to datagrid_autogeneratecolumns.

foreach (var item in dtgResults.Items)
{
    var row = dtgResults.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
    row.Foreground = Brushes.Red;
}

but that doesn't change a think


Solution

  • Add this to your xaml

    <DataGrid Name="dtg" Background="Transparent">
      <DataGrid.Resources>
        <Style TargetType="DataGridCell">
           <EventSetter Event="DataGridCell.Loaded" Handler="DataGridCell_Load"/>
              <Setter Property="Tag" Value="{Binding RelativeSource={RelativeSource AncestorType=DataGrid}}"/>
                <Setter Property="HorizontalAlignment" Value="Right" />
                  </Style>
      </DataGrid.Resources>
    

    and then in code-behind

    private void DataGridCell_Load(object sender, RoutedEventArgs e)
    {
      DataGridCell cell = sender as DataGridCell;
      cell.Foreground = new SolidColorBrush(Colors.Red);
    }