我有一个WPF DataGrid
绑定到我DataView
创建的DataTable
。 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>
转换方法实际上已被调用。然而,我对此感到好奇的是,为什么它会在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();
}
}
这是正确的做事方式吗?
答案 0 :(得分:0)
转换器将获取由于绑定而产生的值。当您使用DataView
作为ItemsSource
时,DataView
由DataRowView
个对象组成。因此,您在转换器中获得DataRowView
作为来源。
答案 1 :(得分:-1)
转换器名称过于通用,可能会出现问题。而是使用&#34; CellStyleConverter&#34;比如说名字。