Hamish Redmond
Hamish Redmond

Reputation: 59

WPF change the background color of an edittable combobox in code

I need to set the background color of an editable combobox in code. This is what I have but does not change the color:

        ComboBox comboBox = sender as ComboBox;
        comboBox.Background = Brushes.PeachPuff;

        if (comboBox.IsEditable == true)
        {
            TextBox textBox = (TextBox)comboBox.Template.FindName("PART_EditableTextBox", comboBox);
            if (textBox != null)
            {
                textBox.Background = Brushes.PeachPuff;

            }
        }

I was expecting the background color to change to PeachPuff (light orange) but nothing happens - any ideas?

Upvotes: 0

Views: 2115

Answers (1)

SamTh3D3v
SamTh3D3v

Reputation: 9944

Changing the combobox's background using the background property only use to work in Win7 and older, in windows 8 and above the default template for the ComboBox has been changed, to fix that you should edit the default template,

  1. using VisualStudio 2013 or Blend, Right Click the combobox and choose EditTemplate > Edit a Copy :

Edit a Copy

  1. In the generated Xaml search for <ControlTemplate TargetType="{x:Type ToggleButton}"> and replace the {StaticResource ComboBox.Static.Background} markup with a TemplateBinding to the Background property, your code should look like this after the update :

     ...
      <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ToggleButton}">
                    <Border x:Name="templateRoot" BorderBrush="{StaticResource ComboBox.Static.Border}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="true">
                        <Border x:Name="splitBorder" BorderBrush="Transparent" BorderThickness="1" HorizontalAlignment="Right" Margin="0" SnapsToDevicePixels="true" Width="{DynamicResource {x:Static SystemParameters.VerticalScrollBarWidthKey}}">
                            <Path x:Name="arrow" Data="F1 M 0,0 L 2.667,2.66665 L 5.3334,0 L 5.3334,-1.78168 L 2.6667,0.88501 L0,-1.78168 L0,0 Z" Fill="{StaticResource ComboBox.Static.Glyph}" HorizontalAlignment="Center" Margin="0" VerticalAlignment="Center"/>
                        </Border>
                    </Border>
                    <ControlTemplate.Triggers>
                        <MultiDataTrigger>
                         ...
    
  2. Now, you can use the Background property to change the Combobox color:

    <Grid>
      <ComboBox IsEditable="True" x:Name="EditableComboBox" Background="PeachPuff" VerticalAlignment="Center" HorizontalAlignment="Center" Width="200" Style="{DynamicResource ComboBoxStyle1}" >
      </ComboBox>
    </Grid>
    

    combobox

Upvotes: 3

Related Questions