Wpf 如何覆盖选定ListBoxItem的前景

Wpf 如何覆盖选定ListBoxItem的前景,wpf,xaml,app.xaml,Wpf,Xaml,App.xaml,我有一个全局样式(Application.Resources)来设置所有文本块的前景 <Style TargetType="{x:Type TextBlock}"> <Setter Property="Foreground" Value="Brown"/> </Style> 这个很好用 现在,我尝试覆盖选定ListBoxItem中TextBlock的前景,它是默认ContentPresenter内容的一部分 我为ListBoxItem创建了一个新

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

<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>

背景效果很好

但前景仍然具有文本块中的笔刷形式de global样式。
在使用绑定的解决方案中,哪种方法是设置前景的最佳方法?

这就是为什么定义隐式应用程序范围的
TextBlock
样式通常是个坏主意的一个例子

但是您应该能够通过向
添加默认样式来覆盖它:


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

但是您应该能够通过向
添加默认样式来覆盖它:



如果要“覆盖选定ListBoxItem中文本块的前景”,为什么不在模板中放置文本块,而不是ContentPresenter?这也是我的第一个想法。但是,那又有什么约束呢
Text=“{Binding}”
如果项是字符串或项类具有适当的ToString方法。否则绑定到item类的某些属性。是的,但是如果我使用
Text=“{Binding}”
绑定它,那么我将丢失
DisplayMemberPath
-功能。如果我将其绑定到模型的特定属性,我需要为每个模型指定一个特定的模板(样式)。如果你想“覆盖选定ListBoxItem中TextBlock的前景”,为什么不在模板中放置一个TextBlock,而不是ContentPresenter?这也是我的第一个想法。但是,那又有什么约束呢
Text=“{Binding}”
如果项是字符串或项类具有适当的ToString方法。否则绑定到item类的某些属性。是的,但是如果我使用
Text=“{Binding}”
绑定它,那么我将丢失
DisplayMemberPath
-功能。如果将其绑定到模型的特定属性,则需要为每个模型指定一个特定的模板(样式)。
<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>