WPF:设置DataGridTextColumn的DataGridCell.BackgroundProperty导致不需要的副作用

yuvru6vn  于 2023-05-08  发布在  其他
关注(0)|答案(1)|浏览(144)

我试图在基础数据源属性具有特定值时设置DataGridTextColumn的背景值。这是可行的,但是当用户选择数据网格中的行时,正常的行为是单元格变为蓝色,但是在这种情况下,没有设置背景(return DependencyProperty.?)单元格保持白色,因为字体颜色在选择时设置为白色,所以看不到值:)

预期:

当选择行时,是否可以保持正常/默认行为?列自动添加到数据网格代码中,以添加BackgroundProperty的转换器:

var column = DtgMatrix.Columns[0] as DataGridTextColumn;
    var style = new Style(typeof(DataGridCell));
    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);
    }
    return DependencyProperty.UnsetValue;
  }

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

mrzz3bfm1#

您可以使用Trigger来仅在单元格未被选中时设置Background属性:

var column = DtgMatrix.Columns[0] as DataGridTextColumn;
var style = new Style(typeof(DataGridCell));
var trigger = new Trigger()
{
    Property = DataGridCell.IsSelectedProperty,
    Value = false
};
trigger.Setters.Add(new Setter(BackgroundProperty, new Binding()
{
    Path = new PropertyPath("SomeFieldName"),
    Converter = new BrushConverter(),
    Mode = BindingMode.OneWay
}));
style.Triggers.Add(trigger);

column.CellStyle = style;

相关问题