[英]Changing Background Color of DataGridCell via IValueConverter
I am using a WPF DataGrid with dynamic columns.我正在使用带有动态列的 WPF DataGrid。 The colums and binding are generated in code behind which is working fine.
列和绑定是在运行良好的代码中生成的。 Now I want to change the background color of the DataGrid cell depending on data
现在我想根据数据更改 DataGrid 单元格的背景颜色
Therefore I created a IValueConverter因此我创建了一个 IValueConverter
public class ValueToBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is DataGridCell dgc)
{
var content = dgc.Content;
var header = dgc.Column.Header;
var index = dgc.Column.DisplayIndex;
}
return DependencyProperty.UnsetValue;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
}
Using it that way:以这种方式使用它:
<UserControl.Resources>
<converters:ValueToBrushConverter x:Key="ValueToBrushConverter"/>
<Style x:Key="CellStyle" TargetType="DataGridCell">
<Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource ValueToBrushConverter}}" />
</Style>
</UserControl.Resources>
<DataGrid Grid.Row="2" x:Name="PartsGrid" AutoGenerateColumns="False" IsReadOnly="True" CanUserSortColumns="True"
BorderBrush="Black" Margin="20 10 0 10"
CellStyle="{StaticResource CellStyle}"
VirtualizingPanel.IsContainerVirtualizable="True"
VirtualizingPanel.VirtualizationMode="Recycling"
VirtualizingPanel.IsVirtualizing="True"
VirtualizingPanel.CacheLengthUnit="Item"
EnableColumnVirtualization = "True"
EnableRowVirtualization = "True"
>
</DataGrid>
Unfortunately I cannot get the showen Value of the gridcell inside the converter.不幸的是,我无法获得转换器内部网格单元的显示值。 Header and DisplayIndex are the, but content is null.
Header 和 DisplayIndex 是,但内容为空。
So whats the proper way to get the value of the gridcell inside the IValueConverter?那么在 IValueConverter 中获取 gridcell 值的正确方法是什么?
Using a Multibinding Converter solved it:使用多重绑定转换器解决了它:
<Style x:Key="CellStyle" TargetType="DataGridCell">
<Setter Property="Background" >
<Setter.Value>
<MultiBinding Converter="{StaticResource ValueToBrushConverterMulti}" >
<Binding Path="." RelativeSource="{RelativeSource Self}"/>
<Binding Path="." RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=DataGridColumn}" />
</MultiBinding>
</Setter.Value>
</Setter>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.