WPF Combobox Background for different selected items

I have a Combobox with Just 3 item: Planing, Progress and Done,

<ComboBox SelectedIndex="0>
    <ComboBoxItem Content="Planing"/>
    <ComboBoxItem Content="Progress"/>
    <ComboBoxItem Content="Done"/>
</ComboBox>

      

How to change the background color of the ComboBox (which does not match the Gradiant) depends on which item is selected.

Example: purple for planing, blue for progress, and green for Done.

Note. I mean ComboBox Background, not a list of ComboBox items.

thank

+3


source to share


1 answer


1) Using the selectionChanged event

You can customize it in the event comboBox_SelectionChanged

private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (comboBox.SelectedItem.ToString() == "Planning")
    {
        comboBox.Background = Brushes.Purple;
    }
    else if (comboBox.SelectedItem.ToString() == "Progress")
    {
        comboBox.Background = Brushes.Blue;
    }
    else if (comboBox.SelectedItem.ToString() == "Done")
    {
        comboBox.Background = Brushes.Green;
    }
}

      

The event comboBox_SelectionChanged

will be triggered every time the selected value in the combo box is changed. Inside, you can just check the value of the selected item and apply the color you want.

This will be xaml Combobox

<ComboBox x:Name="comboBox" SelectionChanged="comboBox_SelectionChanged"/>

      




2) Using DataTriggers in XAML

This can also be done via xaml by setting a few DataTrigger

to Style.Triggers

like this

<ComboBox x:Name="mycombobox">
    <ComboBox.Style>
        <Style TargetType="{x:Type ComboBox}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Path=SelectedItem.Content, ElementName=mycombobox}" Value="Planning">
                    <Setter Property="Background" Value="Purple" />
                </DataTrigger>
                <DataTrigger Binding="{Binding Path=SelectedItem.Content, ElementName=mycombobox}" Value="Progress">
                    <Setter Property="Background" Value="Blue" />
                </DataTrigger>
                <DataTrigger Binding="{Binding Path=SelectedItem.Content, ElementName=mycombobox}" Value="Done">
                    <Setter Property="Background" Value="Green" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ComboBox.Style>
    <ComboBoxItem Content="Planning"/>
    <ComboBoxItem Content="Progress"/>
    <ComboBoxItem Content="Done"/>
</ComboBox>

      

More information on DataTriggers:

Represents a trigger that applies property values ​​or takes action when related data meets a specified condition.

+4


source







All Articles