【问题标题】:Change Displaying color of Icon in a Combo Box更改组合框中图标的显示颜色
【发布时间】:2019-09-14 11:30:54
【问题描述】:

在我的 WPF 应用程序中,我有一个带有图标的组合框,它显示一个具有特定名称的图标。这些图标分别代表名称的类型(我对此没有问题,因此不会详细解释)

我正在尝试设置此组合的样式以确保应用程序的一致性。我在这里要做的是在图标悬停时选择图标颜色#047F89,因为它与我想给它白色的图标颜色相似:

我已经能够实现此要求,但在此过程中,当一个项目未选择或悬停在上时,图标颜色已更改为默认颜色黑色。而不是黑色,我希望它也具有#047F89 的颜色。

我无法弄清楚这里需要做什么,如果有任何帮助,我将不胜感激

这是我的代码

我的风格如下

<Style x:Key="ButtonBackground" TargetType="{x:Type ComboBox}">
    <Setter Property="Foreground" Value="#047F89" />
    <Style.Triggers>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="Foreground" Value="White" />
        </Trigger>
     </Style.Triggers>
</Style>

组合框的使用

<ComboBox Height="10"
          SelectedItem="{Binding Path=SelectedItem, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
          VerticalAlignment="Stretch"
          Style="{StaticResource ButtonBackground}"
          ItemsSource="{Binding Source={StaticResource ItemCollectcion}}">

组合框资源示例

<ComboBox.Resources>
    <DataTemplate DataType="{x:Type FolderModel}">
        <Path Stretch="Uniform" 
              Fill="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Control}, Path=Foreground}"
               Height="15"
               Width="25"
               Data="..."/>
     </DataTemplate>    
</ComboBox.Resources> 

【问题讨论】:

  • 你试过AncestorType=ComboBox吗?否则它可能会找到 ComboBoxItem 祖先。
  • 嗨@Clemens 我试过了......这确实让图标在未选择时显示所需的颜色,但导致图标在选择时未变为白色(如果您查看所附图片你会看到我在说什么
  • 我认为您需要做的是更改您放置在 Combobox 中的项目的“鼠标悬停”视觉样式,而不是 Combobox 样式本身。
  • 按照您的风格,将 TargetType 设为 ComboBoxItem 而不是 ComboBox

标签: c# wpf xaml combobox triggers


【解决方案1】:

ComboBox 样式中的IsSelected 触发器无效,因为 ComboBox 没有这样的属性。

您应该改为为 ComboBoxItem 类声明一个 Style,如下所示,也许还应该为 IsMouseOver 属性添加一个 Trigger。

<Style x:Key="ButtonBackground" TargetType="ComboBoxItem">
    <Setter Property="Foreground" Value="#047F89" />
    <Style.Triggers>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="Foreground" Value="White" />
        </Trigger>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="Foreground" Value="White" />
        </Trigger>
    </Style.Triggers>
</Style>

然后将 Style 赋给 ComboBox 的ItemContainerStyle 属性:

<ComboBox ... ItemContainerStyle="{StaticResource ButtonBackground}"/>

并在DataTemplate中的Binding中使用ComboBoxItem作为AncestorType:

Fill="{Binding Foreground,
       RelativeSource={RelativeSource FindAncestor, AncestorType=ComboBoxItem}}"

【讨论】:

  • 我确实试过这个,但是现在当一个项目被选中时,只显示名称并且图标完全消失了。我尝试使用 Live Visual Tree 来查看图标是否存在,即使它存在,但结果显示图标根本不显示。图标显示在组合框中,但选择时仅显示名称并带有空白空间
  • 如果“SmerterRegister”名称左侧的图标被取消,现在显示的内容与附图类似
  • 顺便说一句,我真的很欣赏您的回答,它确实在一定程度上解决了我的问题,但我不能在此过程中失去工作功能。希望你明白:)
猜你喜欢
  • 2017-12-13
  • 2014-11-02
  • 1970-01-01
  • 2021-02-09
  • 2019-09-05
  • 2016-07-09
  • 1970-01-01
  • 1970-01-01
  • 2019-05-15
相关资源
最近更新 更多