Search code examples
wpfxamlcombobox

Change background colour of a ComboBox in WPF without pasting entire template?


I understand you can right click, Edit Template > Edit a Copy, paste the entire ComboBox template then change a few lines, but is there really not a way to change the background in just a few lines of code?

I was able to achieve it with this code, but that eliminates the dropdown arrow/menu which basically makes it useless.

<Style TargetType="{x:Type ComboBox}">
    <Setter Property="Background" Value="Red" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ComboBox}">
                <Border Background="{TemplateBinding Background}">
                    <ContentPresenter></ContentPresenter>
                </Border>
            </ControlTemplate>
         </Setter.Value>
    </Setter>
</Style>

Solution

  • I am afraid you cannot "override" only a part of a ControlTemplate and given the way the default ControlTemplate of the ComboBox is defined, you cannot simply set or property or create a derived style with a trigger to change the background colour of it. This is explained in detail here.

    What you can do is to change the background of the loaded template element at runtime programmtically:

    private void ComboBox_Loaded(object sender, RoutedEventArgs e)
    {
        ComboBox comboBox = (ComboBox)sender;
        ToggleButton toggleButton = comboBox.Template.FindName("toggleButton", comboBox) as ToggleButton;
        if (toggleButton != null)
        {
            Border border = toggleButton.Template.FindName("templateRoot", toggleButton) as Border;
            if (border != null)
                border.Background = Brushes.Yellow;
        }
    }
    

    XAML:

    <ComboBox Loaded="ComboBox_Loaded">
        <ComboBoxItem Background="Yellow">1</ComboBoxItem>
        <ComboBoxItem Background="Yellow">2</ComboBoxItem>
        <ComboBoxItem Background="Yellow">3</ComboBoxItem>
    </ComboBox>
    

    The other option is to copy the entire template into your XAML markup and edit it as per your requirements.