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

WPF设置DataGridTextColumn单元格背景后选中行显示异常如何解决?

解决方案

问题出在你直接创建了全新的DataGridCell样式,覆盖了WPF默认的DataGridCell样式逻辑,包括行选中时的背景色、前景色触发器。要保留默认选中行为,需让自定义样式继承默认的DataGridCell样式。

修改后的代码如下:

var column = DtgMatrix.Columns[0] as DataGridTextColumn;
// 基于默认DataGridCell样式创建自定义样式,继承默认行为
var style = new Style(typeof(DataGridCell))
{
    BasedOn = Application.Current.FindResource(typeof(DataGridCell)) as Style
};
style.Setters.Add(new Setter(BackgroundProperty, new Binding()
{
    Path = new PropertyPath("SomeFieldName"),
    Converter = new BrushConverter(),
    Mode = BindingMode.OneWay
}));

column.CellStyle = style;

public class BrushConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (!string.IsNullOrWhiteSpace(value as string) && value == "boo")
        {
            return new SolidColorBrush(Colors.LightCoral);
        }
        // 不满足自定义条件时返回UnsetValue,让默认样式(包括选中状态)生效
        return DependencyProperty.UnsetValue;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

关键说明

  • 通过Style.BasedOn继承默认样式,保留WPF原生的IsSelected状态触发器(比如选中时的蓝色背景、白色文字)。
  • 转换器返回DependencyProperty.UnsetValue的逻辑无需修改,这会让WPF在不满足自定义背景条件时,自动使用继承来的默认样式设置。

如果DataGrid位于特定容器(如窗口、用户控件)内,可将Application.Current.FindResource替换为容器上下文的FindResource(比如窗口代码中用this.FindResource(typeof(DataGridCell))),确保正确获取默认样式。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 20:45:24