简体   繁体   中英

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:

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:

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

but this not work for DataGrid of wpf.

how to change this code for 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#:

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". 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). After all if you changed the value of a bound property you have to notify the change of the property ( here ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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