WPF 嵌套样式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13858288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF Nested Styles
提问by Sam_vdd
I have TextBlocks and Comboboxes in my application i want the Textblock foreground to be white and the Combobox Foreground to be Black.
我的应用程序中有 TextBlocks 和 Comboboxes,我希望 Textblock 前景为白色,Combobox Foreground 为黑色。
What i tried was:
我试过的是:
<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>
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)
但是combobox Foreground 还是白色的如何覆盖combobox 中的TextBlock Foreground?(在 CSS 中这很容易,但在 WPF 中不知道)
If i remove the Style for TextBlock everything else changes just fine but when i put the style back every foreground is white.
如果我删除 TextBlock 的样式,其他一切都会改变,但是当我将样式放回时,每个前景都是白色的。
回答by Kek
To nest styles, you can include them in the resources of parent. You could also change the TextBlock.Foreground property of Combobox style
要嵌套样式,您可以将它们包含在父项的资源中。您还可以更改组合框样式的 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>
回答by Johan Larsson
Try setting the style for ComboBoxItem
尝试设置 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>

