WPF 嵌套样式

WPF 嵌套样式

问题描述:

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

I have TextBlocks and Comboboxes in my application i want the Textblock foreground to be white and the Combobox Foreground to be 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>

但是combobox Foreground 还是白色如何覆盖combobox 中的TextBlock Foreground?(在 CSS 中这很容易,但在 WPF 中不知道)

But the combobox Foreground is still white how to override the TextBlock Foreground in the combobox? (In CSS this is easy but no idea in WPF)

如果我删除 TextBlock 的样式,其他一切都会改变,但是当我把样式放回去时,每个前景都是白色的.

If i remove the Style for TextBlock everything else changes just fine but when i put the style back every foreground is white.

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

To nest styles, you can include them in the resources of parent. You could also change the TextBlock.Foreground property of Combobox style

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