c# - 覆盖 ComboBox 中的默认 TextBlock 样式

标签 c# wpf

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

App.xaml

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

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>

我尝试过的事情:

  1. 设置 Combobox.Foreground
  2. 设置 TextElement.Foreground
  3. 设置 TextBlock.Foreground
  4. 在 ComboBox.Resources 中定义另一个隐式 TextBlock 样式
  5. 在 Grid.Resources 中定义另一个隐式 TextBlock 样式
  6. 在 Window.Resources 中定义另一个隐式 TextBlock 样式

最佳答案

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

例如,将您的样式放在 Window.Resources 中将使它适用于所有 <TextBlock>对象,而不是其他控件模板中的文本,例如 ComboBoxButton

我建议将您的样式移动到 Window.Resources ,然后设置 ComboBox 项目的样式,使其具有您想要的任何前景色。

<ComboBox.Resources>
    <Style TargetType="{x:Type ComboBoxItem}">
        <Setter Property="Foreground" Value="Blue" />
    </Style>
</ComboBox.Resources>

如果你想保留在Application.Resources , 那么我怀疑你需要追踪什么 x:Static刷键用于设置TextBlock.Text颜色并覆盖你的 ComboBox.Resources

关于c# - 覆盖 ComboBox 中的默认 TextBlock 样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9034887/

相关文章:

c# - 如何以编程方式在悬停时在面板内显示图片框?

c# - 哪些软件可用于创建服务器端 PDF 文件?

c# - 对列表框中的列表项进行 HitTest

c# - 为什么 ReactiveTest 不遵守此测试中的滴答计数

c# - 来自 C# 的委托(delegate)示例深度混淆

c# - Process.Start() 在 Windows 10/Chrome 上去掉井号和之后的所有内容

.net - 编辑 XAML 时 Visual Studio 2010 随机崩溃

ListBox 内的 WPF ComboBox 文本

c# - 将 ASP.Net Core 集成到 WPF 应用程序中

c# - 递归迭代对象的属性