Search code examples
c#wpf

Changing background color of some rows in a combobox


I have a bound combobox and depending on the values I get back in the records I want to change the background color of certain rows in the combobox. Is this possible and if so how?

A little more clarification. I'm looking at one of the fields in each row and based on its value I want to change the background color. So I could be changing all of the row, some of the rows, or none of the rows.

Thanks


Solution

  • Use the ItemContainerStyle to set the item background color per-row. You can bind to a property in the row's data context, and use an IValueConverter to get the appropriate brush. Eg, assuming that the items have a property "Y":

    <ComboBox>
        <ComboBox.Resources>
            <local:BoolToBrushConverter x:Key="BoolToBrushConverter" />
        </ComboBox.Resources>
        <ComboBox.ItemContainerStyle>
            <Style TargetType="ComboBoxItem">
                <Setter Property="Background" 
                        Value="{Binding Y,Converter={StaticResource BoolToBrushConverter}}" />
            </Style>
        </ComboBox.ItemContainerStyle>
    </ComboBox>
    

    Then the "BoolToBrushConverter" would be something like this:

    public class BoolToBrushConverter: IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return (value as bool? == true) ? Brushes.Green : Brushes.Red;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }