[英]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
,而DataView
由DataRowView
對象組成。 因此,您將DataRowView
作為轉換器中的源。
轉換器名稱過於通用,可能是一個問題。 而是使用“CellStyleConverter”作為名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.