WPF 嵌套样式 [英] WPF Nested Styles

查看:55
本文介绍了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>

这篇关于WPF 嵌套样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆