As part of my data processing I generate a DataTable(column count and row count vary) of the following class
public class DataGridCell
{
public string Text { get; set; }
public string Background { get; set; }
}
My plan is to bind a DataGrid to this DataTable; each cell should display the DataGridCell.Text value and the background color of that cell should be the DataGridCell.Background value.
I have tired the following
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>
This gives me a DataGrid with the cells background set to LightGray but the text displayed is Namespace.DataGridCell
The XAML below errors out as {Binding Path=Background} fails as the context is a DataRowView
XAML
<DataGrid x:Name="dgVolumes" ItemsSource="{Binding}">
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="Background" Value="{Binding Path=Background}"/>
</Style>
</DataGrid.CellStyle>
How do I do this ?
The solution provided here WPF Binding to a DataGrid from a DataTable of Objects and another at Change DataGrid cell colour based on values does not AutoGenerate the columns. They use DataGridTemplateColumn but in my case the columns need to be auto-generated as the number of columns (and rows) will change.
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); }
– Shinva