【问题标题】:How to set background for single cell of datagrid wpf not single row?如何为datagrid wpf的单个单元格而不是单行设置背景?
【发布时间】:2018-04-14 05:39:37
【问题描述】:

我有这段代码,我想更改数据网格单个单元格的背景。

在我的代码中,更改行的背景。

<DataGrid x:Name="dg">
        <DataGrid.CellStyle>
            <Style TargetType="DataGridCell">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Place}"
                                 Value="true">
                        <Setter Property="Background" Value="Yellow"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </DataGrid.CellStyle>
    </DataGrid> 

和 C# 代码:

DataTable dt = new DataTable();
            dt.Columns.Add("Time", typeof(string));
            dt.Columns.Add("Place", typeof(string));
            dt.Rows.Add( "23:00", "true");
            dt.Rows.Add( "21:00", "true");
            dt.Rows.Add( "19:00", "false");
            dg.ItemsSource = dt.AsDataView();

我搜索了它和 DataGridView 的代码:

this.dataGridView1.Rows[0].Cells[1].Style.ForeColor = System.Drawing.Color.Red;

但这不适用于 wpf 的 DataGrid。

如何为 DataGrid wpf 更改此代码?

【问题讨论】:

    标签: c# wpf xaml datagrid


    【解决方案1】:

    这个问题的答案是用C#写这段代码:

    dataGrid.UpdateLayout();
    DataGridRow dgRow = mydatagrid.ItemContainerGenerator.ContainerFromIndex(mydatagrid.SelectedIndex) as DataGridRow;
    DataGridCell cell = mydatagrid.Columns(2).GetCellContent(dgRow).Parent as DataGridCell;
    cell.Background = New SolidColorBrush(Colors.Blue);
    

    【讨论】:

      【解决方案2】:

      您可以通过编程方式设置单元格背景颜色。

      DataGridRow dgRow = mydatagrid.ItemContainerGenerator.ContainerFromIndex(mydatagrid.SelectedIndex) as DataGridRow;
      DataGridCell cell = mydatagrid.Columns(2).GetCellContent(dgRow).Parent as DataGridCell;
      cell.Background = New SolidColorBrush(Colors.Blue);
      

      【讨论】:

      • 感谢您的回答。但它错过了这段代码:dataGrid.UpdateLayout();
      【解决方案3】:

      DataTrigger 绑定到属性 Place 并检查值“true”。我还没有使用数据表,但您似乎尝试绑定到字符串类型的列“Place”。数据网格要么期望 Place 为布尔型,要么期望值为“true”(字符串)。毕竟,如果您更改了绑定属性的值,则必须通知属性的更改(here)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-03-07
        • 1970-01-01
        • 2019-07-06
        • 1970-01-01
        • 2013-01-14
        • 2011-12-12
        • 1970-01-01
        相关资源
        最近更新 更多