【发布时间】:2023-03-17 15:05:01
【问题描述】:
作为数据处理的一部分,我生成以下类的 DataTable(列数和行数不同)
public class DataGridCell
{
public string Text { get; set; }
public string Background { get; set; }
}
我的计划是绑定一个DataGrid到这个DataTable;每个单元格应显示 DataGridCell.Text 值,并且该单元格的背景颜色应为 DataGridCell.Background 值。
我已经厌倦了以下
C#
DataTable dtVolume = new DataTable();
for (int i = 0; i < ColumnNames.Length; i++)
{
dtVolume.Columns.Add(ColumnNames[i]);
}
for (double p = max; p > min; p -= 0.05)
{
var row = dtVolume.NewRow();
for (int i = 0; i < ColumnNames.Length; i++)
{
row[i] = new DataGridCell
{
Text = i,
Background = i % 2 == 0 ? "LightGray" : "Red"
};
}
dtVolume.Rows.Add(row);
}
dgVolumes.DataContext = dtVolume.DefaultView;
XAML
<DataGrid x:Name="dgVolumes" ItemsSource="{Binding}">
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="Background" Value="LightGray"/>
</Style>
</DataGrid.CellStyle>
这给了我一个 DataGrid,单元格背景设置为 LightGray,但显示的文本是 Namespace.DataGridCell
下面的 XAML 出错,因为 {Binding Path=Background} 失败,因为上下文是 DataRowView
XAML
<DataGrid x:Name="dgVolumes" ItemsSource="{Binding}">
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="Background" Value="{Binding Path=Background}"/>
</Style>
</DataGrid.CellStyle>
我该怎么做?
WPF Binding to a DataGrid from a DataTable of Objects 和Change DataGrid cell colour based on values 提供的解决方案不会自动生成列。他们使用 DataGridTemplateColumn 但在我的情况下,列需要自动生成,因为列(和行)的数量会发生变化。
【问题讨论】:
-
您究竟是如何“生成”数据表的?如果您希望任何人能够告诉您您做错了什么,您需要发布此代码。
-
类似于
DataTable dtVolume = new DataTable(); for (int i = 0; i < ColumnNames.Length; i++) { dtVolume.Columns.Add(ColumnNames[i]); } for (double p = max; p > min; p -= 0.05) { var row = dtVolume.NewRow(); for (int i = 0; i < ColumnNames.Length; i++) { row[i] = new DataGridCell{ Text = i, Background = i % 2 == 0 ? "LightGray" : "Red" } } dtVolume.Rows.Add(row); }的东西 -
你的方法行不通。看我的回答。