覆盖组合框中的默认文本块样式
本文关键字:文本 样式 默认 组合 覆盖 | 更新日期: 2023-09-27 18:21:40
我在App.xaml中定义了默认的TextBlock样式,这似乎也会影响ComboBox项的文本颜色。现在,如何显式设置在主窗口中定义的组合框的文本颜色?(我想保留默认样式,但将组合框文本颜色设置为蓝色而不是红色…)
应用程序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>
主窗口.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>
我尝试过的东西:
- 设置组合框.前景
- 设置TextElement.Foreground
- 设置TextBlock.Foreground
- 在ComboBox.Resources中定义另一个隐式TextBlock样式
- 在Grid.Resources中定义另一个隐含的TextBlock样式
- 在Window.Resources中定义另一个隐式TextBlock样式
大多数隐式TextBlock样式将停止在控件边界,除非您将它们放在Application.Resources
中
例如,将样式放在Window.Resources
中会使其适用于所有<TextBlock>
对象,但不适用于其他控制模板(如ComboBox
或Button
)中的文本
我建议将你的样式移到Window.Resources
中,然后将你的组合框项目设置为你想要的任何前景色。
<ComboBox.Resources>
<Style TargetType="{x:Type ComboBoxItem}">
<Setter Property="Foreground" Value="Blue" />
</Style>
</ComboBox.Resources>
如果您想将其保留在Application.Resources
中,那么我怀疑您需要跟踪用于设置TextBlock.Text
颜色的x:Static
笔刷键,并在您的ComboBox.Resources
中覆盖它
您必须在ComboBoxItem 上使用触发器
<Style TargetType="{x:Type ComboBoxItem}">
<Style.Triggers>
<Trigger Property="ComboBoxItem.IsMouseOver" Value="true">
<Setter Property="Foreground" Value="Red"/>
</Trigger>
<Trigger Property="ComboBoxItem.IsMouseOver" Value="false">
<Setter Property="Foreground" Value="Blue"/>
</Trigger>
</Style.Triggers>
</Style>
如果你想让它保持静止,那么
<Style TargetType="{x:Type ComboBoxItem}">
<Setter Property="Foreground" Value="Blue"/>
</Style>