Home > Enterprise >  Changing Background Color of DataGridCell via IValueConverter
Changing Background Color of DataGridCell via IValueConverter

Time:05-19

I am using a WPF DataGrid with dynamic columns. 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

Therefore I created a 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.

So whats the proper way to get the value of the gridcell inside the IValueConverter?

CodePudding user response:

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>
  • Related