数据网格行前景色更改不起作用
本文关键字:不起作用 前景色 数据网 网格 数据 | 更新日期: 2023-09-27 18:34:11
这是 :
如何以编程方式形成可观察集合并将其绑定到数据网格
所以我通过以下方式构建数据网格:
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;
}
但这并不能改变一个想法
将其添加到您的 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);
}