覆盖ComboBox中的默认TextBlock样式

Ere*_*mez 3 c# wpf

我在App.xaml中定义了默认的TextBlock样式,这似乎也会影响ComboBox项的文本颜色。现在,如何在主窗口中显式设置ComboBox的文本颜色?(我想保留默认样式,但组合框的文本颜色为蓝色而不是红色...)

应用程式

<Application x:Class="WpfApplication1.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         StartupUri="MainWindow.xaml">
<Application.Resources>
    <Style TargetType="{x:Type TextBlock}">
        <Setter Property="Foreground" Value="Red" />
    </Style>
</Application.Resources>
Run Code Online (Sandbox Code Playgroud)

MainWindow.xaml

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow">
<Grid>
    <ComboBox Name="comboBox1" SelectedIndex="0" HorizontalAlignment="Left" VerticalAlignment="Top">
        <ComboBoxItem Content = "Item1"/>
        <ComboBoxItem Content = "Item2"/>
        <ComboBoxItem Content = "Item3"/>
    </ComboBox>
</Grid>
Run Code Online (Sandbox Code Playgroud)

我尝试过的事情:

  1. 设置组合框。前景
  2. 设置TextElement.Foreground
  3. 设置TextBlock.Foreground
  4. 在ComboBox.Resources中定义另一个隐式TextBlock样式
  5. 在Grid.Resources中定义另一个隐式TextBlock样式
  6. 在Window.Resources中定义另一个隐式TextBlock样式

Rac*_*hel 5

大多数隐式TextBlock样式将在控件边界处停止,除非您将它们放在 Application.Resources

例如,将样式置于其中Window.Resources将使其应用于所有<TextBlock>对象,但不适用于其他控制模板(如a ComboBox或a)中的文本Button

我建议将您的样式移至Window.Resources,然后对ComboBox项进行样式设置,使其具有所需的任何前景色。

<ComboBox.Resources>
    <Style TargetType="{x:Type ComboBoxItem}">
        <Setter Property="Foreground" Value="Blue" />
    </Style>
</ComboBox.Resources>
Run Code Online (Sandbox Code Playgroud)

如果您想保留它Application.Resources,那么我怀疑您需要跟踪x:Static用于设置TextBlock.Text颜色的画笔键并覆盖您的颜色ComboBox.Resources