Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# DataGrid:使用转换器更改单元格颜色_C#_Wpf_Datagrid - Fatal编程技术网

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

C# DataGrid:使用转换器更改单元格颜色,c#,wpf,datagrid,C#,Wpf,Datagrid,我将一个WPFDataGrid绑定到从DataTable创建的DataView。DataTable单元格是一个自定义对象(TableCellDifference),其中包含一些我想用颜色编码的信息 这是xaml <DataGrid ItemsSource="{Binding Path=SelectedTableView}" Grid.Column="2" <DataGrid.CellStyle> <Style TargetType="{x:Typ

我将一个WPF
DataGrid
绑定到从
DataTable
创建的
DataView
DataTable
单元格是一个自定义对象(
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> 

这是正确的操作方法吗?

转换器名称过于通用,可能会造成问题。例如,使用“CellStyleConverter”作为名称

转换器将接受绑定结果产生的值。当您使用
DataView
作为
ItemsSource
时,
DataView
DataRowView
对象组成。因此,您将在转换器中获得
DataRowView
作为源。

转换器不应该以单元格为目标吗?它似乎是针对行的,我不确定为什么这是预期的行为。
Convert
也是
IValueConverter
的一种接口方法;类名更具体。我不是说命名是个问题@AnjumSKhan的回答是正确的。我只是说正确的命名在易读性方面更好。
    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();
    }
}