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 the if
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.
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"/>
InvalidCastException could be thrown because the DataContext might not have been set yet and hence it is null , or because the Row datacontext is not of the same type as that of System.Data.DataRowView. Simply put a breakpoint and check the value and type of e.Row.DataContext.
For setting the background of a DataGridRow then check:
or
How to set the background color of a DataGrid row in code behind?
this works for me..
e.Row.Background = Brushes.Red
and for invalidCast, I am quite certain that e.Row.DataContext
is not DataRowView please debug and check what are you trying to cast.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.