【问题标题】:How to override Foreground for selected ListBoxItem如何覆盖选定 ListBoxItem 的前景
【发布时间】:2018-08-27 09:20:22
【问题描述】:

我有一个全局样式 (Application.Resources) 来设置所有 TextBlocks 的前景。

<Style TargetType="{x:Type TextBlock}">
    <Setter Property="Foreground" Value="Brown"/>
</Style>

这很好用。

现在我尝试覆盖所选 ListBoxItem 内 TextBlock 的前景,这是默认 ContentPresenter 内容的一部分。

我为 ListBoxItem 创建了一个新的全局样式:

<Style TargetType="ListBoxItem">
    <Setter Property="Foreground" Value="Orange" />
    <Setter Property="Background" Value="Aqua"/>

    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ListBoxItem">
                <Border Background="{TemplateBinding Background}">
                    <ContentPresenter/>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>

    <Style.Triggers>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="Background" Value="Brown" />
            <Setter Property="Foreground" Value="Aqua" />
        </Trigger>
    </Style.Triggers>
</Style>

背景效果很好。

但是 Foreground 仍然具有来自 TextBlock 的全局样式的画笔形式。 在使用 Binding 的解决方案中设置前景的最佳方式是什么?

【问题讨论】:

  • 如果你想“覆盖选定 ListBoxItem 内 TextBlock 的前景” 为什么不在模板内放置一个 TextBlock,而不是 ContentPresenter?
  • 这也是我的第一个想法。但是,那会被什么束缚呢?
  • Text="{Binding}" 如果项目是字符串或项目类具有适当的 ToString 方法。否则绑定到项目类的某些属性。
  • 是的,但是如果我将它与Text="{Binding}" 绑定,那么我将失去DisplayMemberPath-Feature。如果我将它绑定到模型的特定属性,我需要为每个模型一个特定的模板(样式)。

标签: wpf xaml app.xaml


【解决方案1】:

这是一个示例,说明为什么定义一个隐式应用程序范围的 TextBlock 样式通常是一个坏主意。

但是您应该能够通过向&lt;ContentPresenter.Resources&gt; 添加默认样式来覆盖它:

<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="ListBoxItem">
            <Border Background="{TemplateBinding Background}">
                <ContentPresenter>
                    <ContentPresenter.Resources>
                        <Style TargetType="{x:Type TextBlock}" BasedOn="{x:Null}" />
                    </ContentPresenter.Resources>
                </ContentPresenter>
            </Border>
        </ControlTemplate>
    </Setter.Value>
</Setter>

【讨论】:

    猜你喜欢
    • 2021-09-20
    • 2018-01-27
    • 1970-01-01
    • 2018-09-01
    • 2018-10-26
    • 1970-01-01
    • 2021-02-28
    • 1970-01-01
    • 2022-06-11
    相关资源
    最近更新 更多