You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

DataGrid修改行/单元格背景色时多行异常变色问题求助

WPF DataGrid行/单元格背景色异常问题及解决方法

修改WPF DataGrid的行或单元格背景色时出现异常:修改某一行/单元格颜色后,列表下方原本不可见的行也会变色,只有滚动到对应位置才会恢复正常显示。

硬编码修改背景色的示例代码:

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

尝试修改Row和Cell的颜色,结果一致都会触发该异常。


更新

尝试通过数据绑定方式设置行背景色,但颜色需要滚动出视图再返回才会更新:

XAML样式代码:

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

修改颜色的调用代码:

itemlist[x].RowBackGroundColor = "Red";

最终解决方法:为数据实体类实现INotifyPropertyChanged接口后,背景色更新异常问题完全解决。


内容的提问来源于stack exchange,提问作者NOAH

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 16:15:02