简体   繁体   English

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

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

I have this code and I want change background of single cell of datagrid. 我有这段代码,我想更改数据网格的单个单元格的背景。

in my code, change background of 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> 

and C# code: 和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();

I searched about it and this code for DataGridView: 我搜索了一下,并为DataGridView编写了以下代码:

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

but this not work for DataGrid of wpf. 但这不适用于wpf的DataGrid。

how to change this code for DataGrid wpf? 如何更改此代码为DataGrid WPF?

You can set the cell background color programmatically. 您可以通过编程方式设置单元格背景色。

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

The answer of this question is write this code in C#: 这个问题的答案是用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);

The DataTrigger binds to property Place and check for value "true". DataTrigger绑定到属​​性Place,并检查值“ true”。 I haven't used data tables yet but it seems that you try to bind to the column "Place" which is of type string. 我还没有使用过数据表,但是您似乎试图绑定到字符串类型的“位置”列。 The data grid either expects Place to be bool or having the value "true" (string). 数据网格期望Place为bool或值为“ true”(字符串)。 After all if you changed the value of a bound property you have to notify the change of the property ( here ). 毕竟,如果您更改了绑定属性的值,则必须通知该属性的更改( 此处 )。

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

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