C# 更改'的背景色;数据网格&x27;暗藏

C# 更改'的背景色;数据网格&x27;暗藏,c#,wpf,datagrid,background,row,C#,Wpf,Datagrid,Background,Row,我试图在DataGrid行中出现条件时更改该行颜色后面的代码。比如: private void Datagrid_LoadingRow(object sender, DataGridRowEventArgs e) { if((((System.Data.DataRowView)(e.Row.DataContext)).Row.ItemArray[3].ToString()) == "ERROR") e.Row.Background = new SolidColorBru

我试图在
DataGrid
行中出现条件时更改该行颜色后面的代码。比如:

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;
}
这很简单,但不起作用:

  • 我在
    if
    行中得到一个
    InvalidCastException

  • 即使我只写了一行:

    e.Row.Background=新的SolidColorBrush(Colors.Red)

    …它不工作,没有一条线变成红色

  • ---加---

    1对于第一个问题,错误来自以下类型

    (System.Data.DataRowView)(e.Row.DataContext))
    
    e来自哪里

    private void Datagrid_LoadingRow(object sender, DataGridRowEventArgs e)
    
    因此,事件被正确调用,但我无法让行/列项以编程方式更改背景或前景

  • 我不能改变背景,但我可以改变前景。如果你看一下下面的图片,你会发现这些行有不同的颜色。我没有在purpouse上设置任何内容,在xaml中的datagrid定义中也没有任何特殊内容。但这就是我不能设置背景的原因。我怎样才能撤销这个条件?
  • 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,因为DataContext可能尚未设置,因此为null,或者因为行DataContext与System.Data.DataRowView的类型不同。只需放置一个断点并检查e.Row.DataContext的值和类型

    要设置DataGridRow的背景,请选中:

    这对我来说很有用

    e.Row.Background = Brushes.Red
    

    对于invalidCast,我非常确定
    e.Row.DataContext
    不是DataRowView。请调试并检查您试图转换的内容。

    Background=“{x:Null}”??为什么?因为我不想要背景。我的窗口上有一个背景灰色渐变,所有控件作为背景都是透明的(参见最后一张附加的图片)。尝试使用background=transparent代替nullNo更改仍然交替的颜色行