繁体   English   中英

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

[英]DataGrid: change cell color with converter

我有一个 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> 

convert 方法实际上正在被调用。 不过,我很好奇的是,为什么它会像触发器中声明的那样在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();
    }
}

这是正确的做事方式吗?

转换器将获取作为绑定结果的值。 由于您使用DataView作为您的ItemsSource ,而DataViewDataRowView对象组成。 因此,您将DataRowView作为转换器中的源。

转换器名称过于通用,可能是一个问题。 而是使用“CellStyleConverter”作为名称。

暂无
暂无

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

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