繁体   English   中英

如何为DataGrid WPF的单个单元格而不是单行设置背景?

[英]How to set background for single cell of datagrid wpf not single row?

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

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

<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?

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

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);

这个问题的答案是用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);

DataTrigger绑定到属​​性Place,并检查值“ true”。 我还没有使用过数据表,但是您似乎试图绑定到字符串类型的“位置”列。 数据网格期望Place为bool或值为“ true”(字符串)。 毕竟,如果您更改了绑定属性的值,则必须通知该属性的更改( 此处 )。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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