2011-01-12 46 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默認標籤和文本塊黑色,但你可以改變爲藍色,如果你喜歡。