背景:
我有一个ItemSource
绑定到ObservableCollection<Dictionary<string, object>>
类型的 DataGrid。这背后的想法是允许 DataGrid 显示来自不同来源的一堆对象(这是一个日志收集程序,因此字段都因一种类型的日志而异)。我已经通过行为处理了列的生成,所以直到运行时我才知道这些列将是什么。
问题:
我想有一种方法来显示基于字段(列)的条目之间的共性,同时保持来自不同列的排序顺序。为此,我正在考虑使用颜色编码系统。如果 columnA 下的 cellA 中的值与 columnA 中 cellB 的值匹配,则单元格所属的两行对于在两个单元格中找到的值将获得相同的唯一颜色。用户还应该能够将列更改为颜色代码。
我一直在尝试使用一种风格来获得预期的效果,但遇到了一些麻烦。这是有问题的代码。
主窗口.xaml
<DataGrid...>
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="Background">
<Setter.Value>
<MultiBinding Converter="{StaticResource RowBackgroundConverter}">
<MultiBinding.Bindings>
<Binding RelativeSource="{RelativeSource Self}"/>
<Binding Path="ColumnName"/>
<Binding Path="."/>
</MultiBinding.Bindings>
</MultiBinding>
</Setter.Value>
</Setter>
</Style>
</DataGrid.CellStyle>
</DataGrid>
行背景转换器
/// <summary>
/// A converter that changes the background of a DataGrid based on a cell value
/// </summary>
public class RowBackgroundConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (values[0] is DataGridCell)
{
DataGridCell cell= (DataGridCell)values[0];
string columnName = (string)values[1];
Dictionary<string, object> dataGridValues = (Dictionary<string, object>)values[2];
// Check the cell's column name and compare it against the desired column name (columnName) Get the index of the value and get the mapped brush. (dataGridValues[columnName])
return new SolidColorBrush(ColorMap.ColorDictionary[0]);
}
return SystemColors.AppWorkspaceColor;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
在我的 ViewModel 中,我有一个 ColumnName 属性,用于对所需的列进行颜色编码。
问题是当我的多重绑定的上下文是数据网格单元格时,如何在视图模型中访问属性?