簡體   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