Search code examples
c#wpfcolorsdatagrid

DataGrid changing background color changes multiple row color


I am trying to change the Background color of Row or Cells of my DataGridand I am getting some weird, for me, changes. When I change the color of X Row or Cell another Row's down my list will also change. The Rows changing are not Visible unless I scroll down to them. Here is my hardcoded example of the code.

DataGridRow? firstRow = sDataGrid.ItemContainerGenerator.ContainerFromItem(sDataGrid.Items[i]) as DataGridRow;
if( firstRow != null )
{
    DataGridCell? firstColumnInFirstRow = sDataGrid.Columns[0].GetCellContent(firstRow).Parent as DataGridCell;
    if (firstColumnInFirstRow != null)
    {
        firstColumnInFirstRow.Background = Brushes.Green;
        //firstRow.Background = Brushes.Green;
    }
}

Here is an Image of the DataGrid

DataGrid

I tried changing both Row and Cell colors and had same results.

Update

I added a Binding. However the color wont change until it goes out of view and then back to view again.

<DataGrid.RowStyle>
    <Style TargetType="DataGridRow">
        <Setter Property="Background" Value="{Binding RowBackGroundColor}"/>
    </Style>
</DataGrid.RowStyle>

Call

itemlist[x].RowBackGroundColor = "Red";

Added INotifyPropertyChanged. Fixed it. Thank you all


Solution

  • This is because of the UI virtualization that is enabled by default.

    You should either disable it by setting the VirtualizingPanel.IsVirtualizing attached property of the DataGrid to false or better yet avoid setting properties of the visual containers directly and instead use data bindings and triggers in XAML to change the appearance of the cells conditionally.