0

我有一个带有动态生成列的 DataGrid,我需要更改其值在某些操作后发生变化的单元格的样式。

DataGrid 的 ItemsSource 定义为List<MyTableRow>,其中

public class MyTableRow
{
    private string[] _values;
    private string _rowHeader;

    // getters and setters here
}

使用以下代码生成 DataGrid 列:

for (int i = 0; i < source[0].Values.Length; i++)
{
    var col = new DataGridTextColumn();
    var binding = new Binding("Values[" + i + "]");
    col.Binding = binding;
    col.CanUserSort = false;
    this.dataGrid.Columns.Add(col);
    this.dataGrid.Columns[i].Header = columnNames[i];
}

生成的 DataGrid 看起来像这样

当我尝试突出显示 ItemsSource 中的值已更改的单元格(粗体文本或彩色背景)时,就会出现问题。这就是我的问题分为两部分的地方:

  1. 是否有一些“内置”的方式来处理更改的单元格?(也许有ObservableColletion或其他)
  2. 如果不是,我如何根据索引或值突出显示单独的单元格

我尝试使用 xaml 样式和/或触发器来执行此操作,但结果证明我不知道应该将什么值蒙蔽传递给转换器

<Style TargetType="TextBlock">
    <Setter Property="Background" 
            Value="{Binding <!-- some proper binding here -->, 
                    Converter={StaticResource ValueToBrushConverter}}"/>
</Style>

在 SO 上找到的其他解决方案要么具有相同的绑定“问题”,要么就是不起作用。我该怎么做才能突出显示一个单元格而不是整行/列?MyTableRow如有必要,我可以更改 ItemsSource、字段和/或列的生成代码

谁能帮帮我?自从我遇到这个问题以来已经有几天了


更新找到解决方案


4

1 回答 1

1

最后找出如何做我想做的事。该解决方案有点“肮脏”,但对我来说效果很好。我在需要突出显示的每个单元格中添加了不间断的空格字符

private const string NBSP = "\u00A0"

之后剩下要做的就是创造价值转换器。所以我MultiBinding在我的 XAML 中添加了:

<DataGrid.CellStyle>
    <Style TargetType="{x:Type DataGridCell}">
        <Setter Property="Background">
            <Setter.Value>
                <MultiBinding Converter="{StaticResource ValueToBrushMultiConverter}" >
                    <MultiBinding.Bindings>
                        <Binding RelativeSource="{RelativeSource Self}" />
                        <Binding RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGridRow}}" />
                    </MultiBinding.Bindings>
                 </MultiBinding
            </Setter.Value>
        </Setter>
    </Style>
</DataGrid.CellStyle>

Сonverter定义为:

public class ValueToBrushMultiConverter : IMultiValueConverter
    {
        private const string NBSP = "\u00A0";
        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            var cell = (DataGridCell)values[0];
            var dgRow = (DataGridRow)values[1];

            var test = (dgRow.Item as TableRow<string, string>).Values[cell.Column.DisplayIndex];

            if (test.Contains(NBSP))
                return System.Windows.Media.Brushes.PaleGreen;
            return DependencyProperty.UnsetValue;           
        }

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

希望这对某人有帮助!

于 2014-02-27T09:31:15.333 回答