0
votes

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?

3

3 Answers

1
votes

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

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

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