我想根据数据表中绑定到DataGrid的行来为我的DataGrid ColumnHeader着色。 但是我怎么能这样做呢?我在Datagrid.Row上使用的方法不起作用,因为显然没有“Column”属性可以使用。
我想出了这个,所以我可以在Colorconverter中使用整个DataGrid,但我无法找到确定当前呈现哪个Columnheader的方法。
XAML:
<DataGrid x:Name="excelDataTable_ExcelData">
<Style TargetType="DataGridColumnHeader">
<Setter Property="Background" Value="{Binding RelativeSource={RelativeSource AncestorType=DataGrid}, Converter={StaticResource ExcelColumnColorConverter}}"></Setter>
</Style>
</DataGrid>
Colorconverter背后的代码:
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var col = (System.Data.DataColumn)value;
var colStateObj = col.Table.Rows[col.Table.Rows.Count-1][col.ColumnName];
Enums.RowState colorValue = (Enums.RowState)Enum.Parse(typeof(Enums.RowState), colStateObj.ToString());
switch (colorValue)
{
case Enums.RowState.HeaderRow:
return Brushes.Gainsboro;
case Enums.RowState.isIncluded:
return Brushes.LightGreen;
case Enums.RowState.NotIncluded:
return Brushes.LightSalmon;
default:
return Brushes.Azure;
}
}
/// <summary>
/// Converts the value of the hidden Color row to a color on the Data table.
/// </summary>
/// <param name="value">The value</param>
/// <param name="targetType">The type of the binding target.</param>
/// <param name="parameter">The converter parameter.</param>
/// <param name="culture">The culture</param>
/// <returns>
/// EThe converted value or NULL
/// </returns>
/// <exception cref="System.NotImplementedException">Not implemented because it is not needed</exception>
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
答案 0 :(得分:0)
我最终使用Multibinding来解决问题:
XAML:
<Style TargetType="DataGridColumnHeader">
<Setter Property="Background">
<Setter.Value>
<MultiBinding Converter="{StaticResource ExcelColumnColorConverter}">
<Binding RelativeSource="{RelativeSource AncestorType=DataGrid}"></Binding>
<Binding RelativeSource="{RelativeSource self}" Path="Column"></Binding>
</MultiBinding>
</Setter.Value>
</Setter>
</Style>
转换器:
public class ExcelColumnColorConverter : IMultiValueConverter
{
public object Convert(object[] value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (!(value[1] == null))
{
var dgrid = (DataGrid)value[0];
var colHeader = ((DataGridTextColumn)value[1]).Header.ToString();
var dView = (System.Data.DataView)dgrid.ItemsSource;
var table = dView.Table;
var rowstateObj = table.Rows[table.Rows.Count - 1][colHeader];
Enums.RowState colorValue = (Enums.RowState)Enum.Parse(typeof(Enums.RowState), rowstateObj.ToString());
switch (colorValue)
{
case Enums.RowState.HeaderRow:
return Brushes.Gainsboro;
case Enums.RowState.isIncluded:
return Brushes.LightGreen;
case Enums.RowState.NotIncluded:
return Brushes.LightSalmon;
default:
return Brushes.Azure;
}
}
else
{
return null;
}
}