我正在尝试通过使用转换器来更改数据网格单元格颜色,该转换器将单元格作为参数,因为我将需要单元格和行来选择单元格的颜色。数据是动态的因此我没有任何model.Problem是转换器在加载数据时遇到的问题。
private void RDataGrid_AutoGeneratedColumns(object sender, EventArgs e)
{
foreach (var dataGridColumn in RDataGrid.Columns)
{
var textColumn = dataGridColumn as DataGridTextColumn;
if (textColumn == null) continue;
textColumn.ElementStyle = FindResource("gridElementStyle") as Style;
textColumn.EditingElementStyle = FindResource("gridEditElementStyle") as Style;
textColumn.CellStyle = FindResource("gridCellStyle") as Style;
}
}
这是绑定到datagrid的样式。
<Style x:Key="gridCellStyle" TargetType="{x:Type DataGridCell}">
<Setter Property="Background"
Value="{Binding .
, RelativeSource={RelativeSource AncestorType={x:Type DataGridCell}}
,Converter={StaticResource ColorConverter}
}" />
</Style>
转换器:
public class ColorConverter : IValueConverter
{
//private string[,] yourarray = new string[100, 100];
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
DataGridCell cell = (DataGridCell)value;
return Brushes.Red;
//int x = cell.Column.DisplayIndex;
//var parent = VisualTreeHelper.GetParent(cell);
//while (parent != null && parent.GetType() != typeof(DataGridRow))
//{
// parent = VisualTreeHelper.GetParent(parent);
//}
//int y = ((DataGridRow)parent).GetIndex();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
答案 0 :(得分:0)
这对我有用:
<Style TargetType="DataGridCell">
<Setter Property="Foreground" Value="Black"/>
<Setter Property="Background">
<Setter.Value>
<MultiBinding Converter="{StaticResource NameToBrushMultiValueConverter}" >
<MultiBinding.Bindings>
<Binding RelativeSource="{RelativeSource AncestorType=Window}" Path="DataContext"/>
<Binding RelativeSource="{RelativeSource AncestorType=DataGrid}"></Binding>
<Binding RelativeSource="{RelativeSource Self}"/>
</MultiBinding.Bindings>
</MultiBinding>
</Setter.Value>
</Setter>
</Style>