更改' DataGrid'的背景颜色在

时间:2015-12-04 10:37:38

标签: 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 SolidColorBrush(Colors.Red);
    else
        e.Row.Background = null;
}

这很简单,但它不起作用:

  1. 我在InvalidCastException行找到if

  2. 即使我用了一行:

    e.Row.Background = new SolidColorBrush(Colors.Red);

    ......它不起作用,没有一条线变红。

  3. --- --- ADD

    1对于第一个问题,错误来自以下演员

    (System.Data.DataRowView)(e.Row.DataContext))
    

    其中e来自

    private void Datagrid_LoadingRow(object sender, DataGridRowEventArgs e)
    

    所以事件被正确调用但我无法通过编程方式更改背景或前景来获取行/列项。

    1. 我无法改变背景,但我可以改变前景。如果你看一下下面的图片,你会看到那些行有其他颜色。我还没有在purpouse上设置任何内容,xaml中的datagrid定义中也没有任何特殊内容。但这就是为什么我无法设置背景的原因。我该如何撤消这种情况? enter image description here
    2. 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"/> 
      

2 个答案:

答案 0 :(得分:0)

可能会抛出InvalidCastException,因为DataContext可能尚未设置,因此它为null,或者因为Row datacontext与System.Data.DataRowView的类型不同。只需设置一个断点并检查e.Row.DataContext的值和类型。

要设置DataGridRow的背景,请检查:

WPF Datagrid set selected row

How to set the background color of a DataGrid row in code behind?

答案 1 :(得分:0)

这对我有用..

e.Row.Background = Brushes.Red

对于invalidCast,我很确定e.Row.DataContext不是DataRowView,请调试并检查你想要播放的是什么。

相关问题