I have a WPF datagrid that is filled with an ObserverableCollection.
Now I want to color the rows depending on the row content at the program start and if something
To change it through code instead of a trigger it could look something like below. You can access the data as an array and then compare it. In this example I am comparing the 4th column to see if it is greater than 0 and the 5th column to see if it is less than 0 otherwise just paint it the default color. The try/catch it there becuase some logic needs to be added to see if it is a valid row or not.....or you can just ignore the errors as below (not really good practice though) but should be usable as is.
private void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
{
try
{
if (Convert.ToDouble(((System.Data.DataRowView)(e.Row.DataContext)).Row.ItemArray[3].ToString()) > 0)
{
e.Row.Background = new SolidColorBrush(Colors.Green);
}
else if (Convert.ToDouble(((System.Data.DataRowView)(e.Row.DataContext)).Row.ItemArray[4].ToString()) < 0)
{
e.Row.Background = new SolidColorBrush(Colors.Red);
}
else
{
e.Row.Background = new SolidColorBrush(Colors.WhiteSmoke);
}
}
catch
{
}
}
Use the RowStyle. You can use the Triggers to change the color conditionally, or just bind it to a Brush
property on your items and change that property respectively.