Datagrid行前景颜色更改不起作用

时间:2016-02-11 17:45:42

标签: c# wpf datagrid row foreground

这是继续:

  

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

所以我通过以下方式构建了一个datagrid:

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);

所以现在我希望能够在这里更改前景色,而不必去datagrid_autogeneratecolumns。

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

但这不会改变思考

1 个答案:

答案 0 :(得分:1)

将此添加到您的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>

然后在代码隐藏

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