简体   繁体   中英

Change background colour of 'DataGrid' in code behind

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:

  1. I get an InvalidCastException on the if line.

  2. 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.

  1. 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"/> 

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:

WPF Datagrid set selected row

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM