2012-12-13 96 views
1

我在我的应用程序中有TextBlocks和组合框,我希望Textblock前景为白色,而Combobox Foreground为黑色。WPF嵌套样式

我的尝试是:

<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的前景在ComboBox? (在CSS中,这很容易,但在WPF中不知道)

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

+0

对我的作品...你能张贴整个XAML代码,或者至少是相关部分? –

+0

我知道这是一个老问题,但我认为它不工作,因为ComboBox的模板包含一个TextBox,它正在通过您的全局风格进行样式化。我认为如果你把全球风格拿出来,凯克的答案将会奏效。 – HiredMind

回答

8

要嵌套样式,可以将它们包含在父项的资源中。 你也可以改变的组合框风格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> 
+0

仍然不起作用 –

+0

怪异....然后我同意@Florian GI:必须有别的东西 – Kek

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

当我改变组合框项目的背景颜色时,它的工作原理,但前景不会改变。 –

+0

这很奇怪,我在这里尝试时看到倒置的颜色。你确定你在ResourceDictionary中引用样式而不是本地样式吗? –

+0

是的,因为如果我删除文本块的样式属性更改正确。 –