Search code examples
wpfxaml

Use IValueConverter to Color DataGridCell


I have a DataGrid in my WPF-Application. There i have to color the rows depending on the data in the row. For this i wrote a ValueConverter and it works. For each possible color i have an DataTrigger in my XAML:

<DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource ColorCellValueConverter}}" Value="Case1">
    <Setter Property="Background" Value="Yellow" />
</DataTrigger>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource ColorCellValueConverter}}" Value="Case2">
    <Setter Property="Background" Value="LightGreen" />
</DataTrigger>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource ColorCellValueConverter}}" Value="Case3">
    <Setter Property="Background" Value="Orange" />
</DataTrigger>

My question is: is it possible to make this better? Is there the possibility to call the converter once and the decide how to color (like a switch-statement)? Or it is possible to bind the return-value of the converter to the setter? So i could return the color und it would also work. Something like this:

<DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource ColorCellValueConverter}}">
    <Setter Property="Background" Value=CONVERTER_RETURN_VALUE />
</DataTrigger>

Thanks for your help and ideas!


Solution

  • As Clemens wrote binding the converter directly on the background is the solution. Works great! Thanks a lot.