2011-01-12 87 views
0

我在App.xaml中为Label定义了样式。无法覆盖WPF中的标签样式

<Application.Resources> 
    <ResourceDictionary> 
     <Style TargetType="Label" > 
      <Setter Property="Foreground" Value="Blue"/> 
     </Style> 
     <Style TargetType="TextBlock" > 
      <Setter Property="Foreground" Value="Blue"/> 
     </Style> 
    </ResourceDictionary> 
</Application.Resources> 

适用于我的MainWindow.xaml中的标签Control的样式。但是当我试图在控件上明确设置Foreground时,它不起作用(我想知道)。 App.xaml中定义的颜色仍然适用(仅用于标签)。

<Grid> 
    <Label Content="Label" Foreground="Black" HorizontalAlignment="Center" VerticalAlignment="Center"/> 
    <TextBlock Text="TextBlock" Foreground="Black" VerticalAlignment="Bottom" Height="15.96" Margin="257.537,0,270.003,86" /> 
</Grid> 

相同的逻辑适用于Textblock和所有控件。有什么建议吗?

回答

5

LabelForeground会显示为蓝色,因为样式为TextBlock的

<Style TargetType="TextBlock" > 
    <Setter Property="Foreground" Value="Blue"/> 
</Style> 

可以在

Differences between Label and TextBlock

+0

绝对正确。谢谢...:) – Jawahar 2011-01-12 06:14:16

3

这是一个交代检查有关更多细节设置,但不是解决方案;)

<Style TargetType="{x:Type TextBlock}"> 
    <Setter Property="FontFamily" 
      Value="Tahoma" /> 
    <Setter Property="FontSize" 
      Value="{StaticResource StandardFontSize}" /> 
    <Setter Property="Foreground" 
      Value="Black" /> 
    <Setter Property="VerticalAlignment" 
      Value="Center" /> 
    <Setter Property="HorizontalAlignment" 
      Value="Left" /> 
</Style>  
<Style TargetType="{x:Type Label}"> 
    <Setter Property="Foreground" 
      Value="Black" /> 
    <Setter Property="ContentTemplate"> 
     <Setter.Value> 
      <DataTemplate> 
       <TextBlock Text="{Binding}" 
          Foreground="{Binding RelativeSource={RelativeSource AncestorType=Label}, Path=Foreground}" /> 
      </DataTemplate> 
     </Setter.Value> 
    </Setter>    
</Style> 

如果你定义你这样的样式,那么你也可以在你的网格中设置/覆盖你的Label Foreground。所以这些styels默认标签和文本块黑色,但你可以改变为蓝色,如果你喜欢。