[英]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.