更新后WPF DataGrid单元格样式更改

时间:2014-02-26 11:08:10

标签: c# wpf data-binding datagrid xaml-binding

我有一个带有动态生成列的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看起来像this

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

  1. 是否有一些“内置”的方式来改变细胞? (可能是ObservableColletion或其他)
  2. 如果不是,我如何根据其索引或值来突出显示单独的单元格
  3. 我尝试使用xaml样式和/或触发器执行此操作,但事实证明我不知道我应该将哪些值传递给转换器

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

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

    任何人都可以帮帮我吗?我坚持这个问题已经过了几天


    更新找到解决方案


1 个答案:

答案 0 :(得分:1)

最后找出如何做我想做的事。解决方案有点“脏”,但对我来说工作正常。 我为每个需要突出显示的单元格添加了不间断的空格字符

private const string NBSP = "\u00A0"

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

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

希望这有助于某人!