【问题标题】:Change background colour of 'DataGrid' in code behind在后面的代码中更改“DataGrid”的背景颜色
【发布时间】:2015-12-04 10:37:38
【问题描述】:

当该行中的条件发生时,我正在尝试更改 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. 我在if 行收到InvalidCastException

  2. 即使我写了一行:

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

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

---添加---

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

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

e 来自哪里

private void Datagrid_LoadingRow(object sender, DataGridRowEventArgs e)

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

  1. 我无法更改背景,但可以更改前景。如果你看一下下面的图片,你会发现这些行有不同的颜色。我没有设置任何目的,xaml 中的数据网格定义也没有任何特别之处。但这就是我无法设置背景的原因。我怎样才能撤消这种情况?

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

【问题讨论】:

    标签: c# wpf datagrid background row


    【解决方案1】:

    可能会抛出 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?

    【讨论】:

      【解决方案2】:

      这对我有用..

      e.Row.Background = Brushes.Red
      

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

      【讨论】:

      • 跨度>
      • Background="{x:Null}" ??为什么?
      • 因为我不想要背景。我的窗口上有一个背景灰色渐变,并且所有控件作为背景都是透明的(参见最后附上的图片)。
      • 尝试背景=透明而不是空
      • 没有变化仍然交替的颜色行
      猜你喜欢
      • 2014-04-08
      • 1970-01-01
      • 2012-03-22
      • 2010-09-24
      • 2020-11-23
      • 1970-01-01
      • 2013-06-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多