C# DataGrid:使用转换器更改单元格颜色
我将一个WPFC# 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
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();
}
}