I am trying to change in code behind the colour of a row of a DataGrid
when a condition in that row occurs. Something like:
private void Datagrid_LoadingRow(object sender, DataGridRowEventArgs e)
{
if((((System.Data.DataRowView)(e.Row.DataContext)).Row.ItemArray[3].ToString()) == "ERROR")
e.Row.Background = new SolidColorBrush(Colors.Red);
else
e.Row.Background = null;
}
That is very simple but it doesn't work:
I get an
InvalidCastException
on theif
line.Even if I put a single line with:
e.Row.Background = new SolidColorBrush(Colors.Red);
...it doesn't work and none of the lines turn red.
---ADD---
1 For the first problem the mistake comes from the following cast
(System.Data.DataRowView)(e.Row.DataContext))
where e comes from
private void Datagrid_LoadingRow(object sender, DataGridRowEventArgs e)
so the event is correctly called but I can't get the row / column item to programmatically change the background or foreground.
- I can't change the background but I can change the foreground. If you take a look at the following picture you will the that rows have alternate colours. I haven't set anything on purpouse nor there is anything particular in the datagrid definition in the xaml. But this is the reason why I can't set the background. How can I undo this condition?
XAML -
<DataGrid x:Name="dtgEventsPCDmis" Grid.Row="6" FontSize="12" Background="{x:Null}" BorderBrush="Gainsboro" VerticalContentAlignment="Stretch" BorderThickness="5" Margin="10,21.4,9.6,0" LoadingRow="Datagrid_LoadingRow" AutoGeneratingColumn="Datagrid_AutoGeneratingColumn" VerticalAlignment="Top" Height="139" RenderTransformOrigin="0.5,0.5" GridLinesVisibility="All"/>