更改ComboBoxItem的前景颜色

本文关键字:颜色 ComboBoxItem 更改 | 更新日期: 2023-09-27 18:20:04

我正在尝试更改ComboBoxItem的前景色,但它不适用,我做错了什么?此外,我正在尝试更改ComboBoxItem上悬停的前景色,但效果不佳。

这是我的xaml:

<ComboBox x:Name="tab5_2_num"  ItemsSource="{Binding}" FontSize="13" FontFamily="/WPF;component/Font/#Agency FB" Margin="722,46,406,281" BorderThickness="1,1,1,4" Height="30">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <Label Content="{Binding}"  />
        </DataTemplate>
    </ComboBox.ItemTemplate>
    <ComboBox.ItemContainerStyle>
        <Style TargetType="{x:Type ComboBoxItem}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type ComboBoxItem}">
                        <Label x:Name="lblCombo" Foreground="Black" FontFamily="/WPF;component/Font/#Agency FB" FontSize="13" Height="20" />
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsMouseOver" Value="True">
                                <Setter TargetName="lblCombo" Property="Background" Value="#FFF01F1F"/>
                                <Setter TargetName="lblCombo" Property="Foreground" Value="White" />
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ComboBox.ItemContainerStyle>
</ComboBox>

更改ComboBoxItem的前景颜色

由于在ComboBoxItem的模板中设置了Label,因此在DataTemplate中设置的Label将不起作用。所以请尝试以下代码:

<ComboBox x:Name="tab5_2_num" Height="30" BorderThickness="1,1,1,4" FontFamily="/WPF;component/Font/#Agency FB" FontSize="13" ItemsSource="{Binding}">
    <ComboBox.ItemContainerStyle>
        <Style TargetType="{x:Type ComboBoxItem}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type ComboBoxItem}">
                        <Label x:Name="lblCombo" Content="{Binding}" FontFamily="/WPF;component/Font/#Agency FB" FontSize="13" Foreground="Black" />
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsMouseOver" Value="True">
                                <Setter TargetName="lblCombo" Property="Background" Value="#FFF01F1F" />
                                <Setter TargetName="lblCombo" Property="Foreground" Value="White" />
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ComboBox.ItemContainerStyle>
</ComboBox>

它应该起作用。

首先,我想知道您是否看到了Label的内容。您可能需要以下内容:

<Label Content={Binding} ... />