【问题标题】:WPF ComboBox, setting the background color of current itemWPF ComboBox,设置当前项的背景颜色
【发布时间】:2019-09-01 19:05:24
【问题描述】:

在我的 WPF 应用程序中,我需要设置组合框的背景颜色。

Example

正如您在附加文件中看到的,我将背景颜色设置为蓝色(在后面的代码中):

_combobox.Background = Brushes.DodgerBlue;

我还设置了触发器,以便在选择项目时处理事件(为 ComboBox 和 ComboBoxItem 设置样式:

<Style x:Key="CmbStyleItem" TargetType="{x:Type ComboBoxItem}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ComboBoxItem}">
                <Border x:Name="gd" Background="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ComboBox}}, Path=Background}" Padding="4,6,2,2">
                    <ContentPresenter />
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="ComboBoxItem.IsMouseOver" Value="True">
                        <Setter TargetName="gd" Property="Background" Value="#E7E2E2" />
                        <Setter TargetName="gd" Property="TextElement.Foreground" Value="#000000"/>
                    </Trigger>
                    <Trigger Property="ComboBoxItem.IsSelected" Value="True">
                        <Setter TargetName="gd" Property="Background" Value="#D6D6D6" />
                        <Setter TargetName="gd" Property="TextElement.Foreground" Value="#000000" />
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
<Style TargetType="{x:Type ComboBox}">
    <Setter Property="HorizontalAlignment" Value="Stretch" />
    <Setter Property="VerticalAlignment" Value="Center" />
    <Setter Property="Width" Value="Auto" />
    <Setter Property="Height" Value="27" />
    <Setter Property="Padding" Value="4,6,2,2" />
    <Setter Property="FontFamily" Value="{StaticResource fntConsole}" />
    <Setter Property="Typography.Capitals" Value="AllSmallCaps"/>
    <Setter Property="FontSize" Value="13.55" />
    <Setter Property="Background" Value="Transparent" />
    <Setter Property="BorderThickness" Value="0" />
    <Setter Property="ItemContainerStyle" Value="{DynamicResource CmbStyleItem}"/>
</Style> 

基本上我无法设置所选项目的背景颜色,例如在附件中,项目“Tav1800x650x18”。有什么提示吗?

【问题讨论】:

  • 看看这个thread 你应该覆盖SelectionBoxItem 和它的模板

标签: wpf combobox


【解决方案1】:

如果我理解你的问题,你想在没有选中项时修改组合框的背景颜色:

所以你有这条线&lt;Setter Property="Background" Value="Transparent" /&gt; 它给出了默认的背景颜色

你必须用你想要的颜色设置Value

或者我误会你了.....

【讨论】:

  • 我试过设置,但它不起作用。我不知道是否必须在 ComboBox 或 ComboBoxItem 上设置属性
  • 你是如何在 xaml 中定义你的组合框的?如果您在 xaml 中设置值,则在我的应用中可以...
  • 一件事当你改变背景时,你改变了组合中所有线条的背景,而不仅仅是第一...
【解决方案2】:

替换: Background="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ComboBox}}, Path=Background}"

收件人:Background="{TemplateBinding Background}"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-03
    • 1970-01-01
    • 2012-04-11
    • 1970-01-01
    • 2014-03-14
    • 1970-01-01
    相关资源
    最近更新 更多