WPF嵌套样式

时间:2012-12-13 10:53:05

标签: wpf styles wpf-controls styling

我的应用程序中有TextBlocks和Comboboxes我希望Textblock前景为白色,Combobox前景为Black。

我试过的是:

    <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

<Style TargetType="{x:Type TextBlock}">
    <Setter Property="Foreground" Value="White" />
</Style>
<Style TargetType="{x:Type ComboBox}">
    <Setter Property="Foreground" Value="Red" />
</Style>
</ResourceDictionary>



<Grid Background="Black">
    <TextBlock Height="23" HorizontalAlignment="Left" Margin="27,30,0,0" Name="textBlock1" Text="TextBlock" VerticalAlignment="Top" />
    <ComboBox Height="23" HorizontalAlignment="Left" Margin="12,99,0,0" Name="comboBox1" VerticalAlignment="Top" Width="120" />
</Grid>

但是组合框前景仍然是白色如何覆盖组合框中的TextBlock前景? (在CSS中这很容易,但在WPF中不知道)

如果我删除StyleBlock的样式,其他所有内容都会改变,但是当我把样式放回去时,每个前景都是白色的。

2 个答案:

答案 0 :(得分:11)

要嵌套样式,可以将它们包含在父级资源中。 您还可以更改Combobox样式的TextBlock.Foreground属性

<Style TargetType="{x:Type ComboBox}">
    <Style.Resources>
        <Style TargetType="{x:Type TextBlock}">
            <Setter Property="Foreground" Value="Black" />
        </Style>
    </Style.Resources>
    <Setter Property="Foreground" Value="Black" />
    <Setter Property="textBlock.Foreground" Value="Black" />
</Style>

答案 1 :(得分:1)

尝试设置ComboBoxItem的样式

<Style TargetType="{x:Type TextBlock}">
    <Setter Property="Foreground" Value="White"/>
    <Setter Property="Background" Value="Black"/>
</Style>
<Style TargetType="{x:Type ComboBoxItem}">
    <Setter Property="Foreground" Value="White"/>
    <Setter Property="Background" Value="Black"/>
</Style>
<Style TargetType="{x:Type ComboBox}">
    <Setter Property="Foreground" Value="White"/>
    <Setter Property="Background" Value="Black"/>
</Style>