简体   繁体   English

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

[英]DataGrid: change cell color with converter

I have a WPF DataGrid bound to a DataView I create from a DataTable .我有一个 WPF DataGrid绑定到我从DataTable创建的DataView The DataTable cells are a custom object ( TableCellDifference ) that have some information I'd like to color code. DataTable单元格是一个自定义对象 ( TableCellDifference ),其中包含一些我想为代码着色的信息。

Here is the xaml这是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> 

The convert method is actually getting called. convert 方法实际上正在被调用。 What I'm curious about, though, is why it's getting called on DataRowView rather than a DataGridCell , as declared in the trigger.不过,我很好奇的是,为什么它会像触发器中声明的那样在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();
    }
}

Is this the correct way of doing things?这是正确的做事方式吗?

Converter will take the value coming as a result of Binding.转换器将获取作为绑定结果的值。 As you are using DataView as your ItemsSource , and DataView is comprised of DataRowView objects.由于您使用DataView作为您的ItemsSource ,而DataViewDataRowView对象组成。 So, you are getting DataRowView as source in your Converter.因此,您将DataRowView作为转换器中的源。

The converter name is too much generic and can be a problem.转换器名称过于通用,可能是一个问题。 Instead use "CellStyleConverter" as name for example.而是使用“CellStyleConverter”作为名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM