Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Change Combobox Background Color while Clicked(ComboBox is Open) in WPF?

Can anybody knows,

How to Change Combobox Background Color while Clicked(ComboBox is Open) in WPF?

like image 759
Nimesh Avatar asked Feb 12 '13 05:02

Nimesh


People also ask

What is combo box WPF?

A combobox is a selection control that combines a non-editable textbox and a drop-down listbox that allows users to select an item from a list. It either displays the current selection or is empty if there is no selected item.


1 Answers

Here's a slightly naive approach:

<ComboBox
  ItemsSource="{x:Static Fonts.SystemFontFamilies}"
  Width="100"
  >
  <ComboBox.Style>
    <Style TargetType="ComboBox">
      <Setter Property="Background" Value="Green" />
      <Style.Triggers>
        <Trigger Property="IsDropDownOpen" Value="True">
          <Setter Property="Background" Value="Red" />
        </Trigger>
      </Style.Triggers>
    </Style>
  </ComboBox.Style>
</ComboBox>

Initially, this sets the Background property to Green, but arranges for it to go to Red when the drop-down appears. However, there are two problems with this:

  1. In some Windows themes (e.g., the Aero theme used in Vista and Windows 7), the green background gets obscured by the bluish colour that theme uses to indicate that the dropdown's button has been pressed. So the button will briefly go green before fading to Cyan.
  2. The ComboBox.Background property only affects the appearance of the button itself, and not the dropdown list. It's possible that what you actually want to do is change the background colour of the part that pops down.

If 2 is what you wanted, this does the trick:

<ComboBox
  ItemsSource="{x:Static Fonts.SystemFontFamilies}"
  Width="100"      >
  <ComboBox.Resources>
    <Style TargetType="ComboBoxItem">
       <Setter Property="Background" Value="Orange" />
    </Style>
  </ComboBox.Resources>
</ComboBox>

Strictly speaking, that's actually changing the background colour of the ComboBoxItem controls that appear in the dropdown but that will have the desired effect.

If you want to fix 1, though, you'll need a custom templates, because the built-in ComboBox template doesn't really provide very good support for the Background property, because it changes the colour of the button part under various circumstances. The Aero theme's look for a ComboBox really isn't designed to support a custom background colour, so you'd need to create your own custom look for the control.

like image 146
Ian Griffiths Avatar answered Oct 13 '22 16:10

Ian Griffiths