DataGrid:使用转换器更改单元格颜色

时间:2015-12-22 15:48:09

标签: c# wpf datagrid

我有一个WPF DataGrid绑定到我DataView创建的DataTableDataTable单元格是一个自定义对象(TableCellDifference),它有一些我想要颜色代码的信息。

这是xaml

<DataGrid ItemsSource="{Binding Path=SelectedTableView}" Grid.Column="2" 
    <DataGrid.CellStyle>
        <Style TargetType="{x:Type DataGridCell}">
            <Style.Setters>
                <Setter Property="Background" Value="{Binding Converter={StaticResource converter}}" />
            </Style.Setters>
        </Style>
    </DataGrid.CellStyle>
</DataGrid> 

转换方法实际上已被调用。然而,我对此感到好奇的是,为什么它会在DataRowView而不是DataGridCell上被调用,如触发器中所声明的那样。

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var dataRow = value as DataRowView;
        if (dataRow == null) return null;

        // why does the cast to DataRowView succeed? It
        // seems like this method should be targeting the cell objects
        foreach (object item in dataRow.Row.ItemArray) 
        {
            var cast = item as TableCellDifference;
            if (cast == null) continue;

            switch(cast.Type)
            {
                case TableCellDifferenceType.Addition:
                    return Brushes.LightGreen;

                case TableCellDifferenceType.Mismatch:
                case TableCellDifferenceType.Omission:
                    return Brushes.Red;

                default:
                    return Brushes.White;
            }
        }
        return null;
    }

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

这是正确的做事方式吗?

2 个答案:

答案 0 :(得分:0)

转换器将获取由于绑定而产生的值。当您使用DataView作为ItemsSource时,DataViewDataRowView个对象组成。因此,您在转换器中获得DataRowView作为来源。

答案 1 :(得分:-1)

转换器名称过于通用,可能会出现问题。而是使用&#34; CellStyleConverter&#34;比如说名字。