Search code examples
xamluser-interfacewinui-3

How to style a combobox control on event in WinUI 3


I'm trying to style a combobox in WinUI 3. When I hover over the combobox the background changes to transparent which is bad since the combobox text is white and the window background is white meaning the text is not visible.

I want to change the ComboBoxBackgroundPointerOver or foreground the so the text doesn't disappear into the window background.

Does anyone know a good way to do this?

Style:

<Style x:Key="ComboBoxStyle" TargetType="ComboBox">
        <Setter Property="Foreground" Value="#FFFFFF" />
        <Setter Property="Background" Value="#BF311A" />
        <Setter Property="BorderBrush" Value="#58585A" />
        <Setter Property="FontWeight" Value="Normal"/>
        <Setter Property="BorderThickness" Value="1" />
        <Setter Property="MaxDropDownHeight" Value="200"/>
        <Setter Property="MinWidth" Value="200"/>
        <Setter Property="Padding" Value="10"/>
        <Setter Property="ItemContainerStyle">
            <Setter.Value>
                <Style TargetType="ComboBoxItem">
                    <Setter Property="Background" Value="#7E1416"/>
                    <Setter Property="Foreground" Value="#FFFFFF"/>
                    <Setter Property="BorderThickness" Value="0"/>
                    <Setter Property="VerticalAlignment" Value="Bottom"/>
                    <Setter Property="Padding" Value="10"/>
                </Style>
            </Setter.Value>
        </Setter>
    </Style>

I've looked all over and it seems like the only way to go is to use ControlTemplates which seems to me like overkill since you are basically redesigning the control at that point.

I've also tried VisualStateManager and changing Combobox.Resource values which I haven't got working and is a poor choice since I want the colours to be set by style.

Style.Triggers doesn't seem to be supported in WinUI 3.

I'm surprised this doesn't work but the solution is still not ideal since I want this all done by Style

    <ComboBox
            ItemsSource="{Binding Runs}"
            Style="{StaticResource ComboBoxStyle}">
        <ComboBox.Resources>
            <Color x:Key="BlackColour">#000000</Color>
            <Color x:Key="WhiteColour">#FFFFFF</Color>
            <StaticResource x:Key="ComboBoxBackgroundPointerOver" ResourceKey="BlackColour"/>
            <StaticResource x:Key="ComboBoxBackground" ResourceKey="BlackColour"/>
        </ComboBox.Resources>
    </ComboBox>

Solution

  • Try making your Style based on DefaultComboBoxStyle. Then you'll be able to override static resources like ComboBoxForegroundPointerOver.

    <SolidColorBrush
        x:Key="ComboBoxForegroundPointerOver"
        Color="Black" />
    <Style
        x:Key="ComboBoxStyle"
        BasedOn="{StaticResource DefaultComboBoxStyle}"
        TargetType="ComboBox">
        ...
        ...
    </Style>