I’m making a WPF program which is able to color the rows in a DataGrid one by one in red using the for loop and I’ve encountered something weird. If the DataGrid has more than 40 rows of data from a database table, it doesn’t color all the rows.
Here’s the code I’m using.
private void Red_Click(object sender, RoutedEventArgs e)
{
for (int i = 0; i < dataGrid1.Items.Count; i++)
{
DataGridRow row = (DataGridRow)dataGrid1.ItemContainerGenerator.ContainerFromIndex(i);
if (row != null)
{
row.Background = Brushes.Red;
}
}
}
Is there any other way to color the rows one by one through other methods or is this some kind of fault in wpftoolkit?
If you want to define colours for each row and you have a property on the items the rows display you can use an ItemsContainerStyle to set the row colour. In the example below you would have a property called ItemColour on your items in the grid which would define the background row colour. The binding binds from the row to the item the row contains.
But you might not want a property ItemColour on your items as they might be your business model. This is where a ViewModel comes into its own. you define a middle layer that wraps your business layer and the ItemColour property based on some custom logic.