2017-09-05 139 views
-1

我有一個默認的標籤樣式爲什麼我無法重寫默認的BasedOn樣式? WPF

<Style x:Key="LabelStyle" TargetType="{x:Type Label}"> 
<Setter Property="FontFamily" Value="Segoe UI" /> 
<Setter Property="FontSize" Value="13.333" /> 
<Setter Property="Foreground" Value="{StaticResource ForegroundBrush}" /> 
<Setter Property="IsTabStop" Value="False" /> 
<Setter Property="HorizontalContentAlignment" Value="Left" /> 
</Style> 

<Style BasedOn="{StaticResource LabelStyle}" TargetType="{x:Type Label}" /> 

然後我嘗試用不同的風格單個標籤

<Style x:Key="HeaderLabelStyle" TargetType="{x:Type Label}"> 
    <Setter Property="FontFamily" Value="Segoe UI" /> 
    <Setter Property="FontSize" Value="16" /> 
    <Setter Property="Foreground" Value="{StaticResource HeaderForegroundBrush}" /> 
    <Setter Property="IsTabStop" Value="False" /> 
    <Setter Property="HorizontalContentAlignment" Value="Left" /> 
    </Style> 

<Label Content="Text here" Name="someName" Style="{StaticResource HeaderLabelStyle}"/> 

但由於某些原因的標籤總是得到默認的樣式。爲什麼?這可以被覆蓋嗎?

感謝

+1

你的風格在哪裏? 'Application.Resources','Window.Resources'等等?它可能是[this](https://stackoverflow.com/q/9035878/302677)是問題。 – Rachel

+0

是的,除非你想讓一個隱式樣式全局應用於整個應用程序,否則我建議將它放在'Window.Resources'中。 'Application.Resources'中的所有內容都應該有一個'x:Key',或者實際上是全局的。 – Rachel

+0

很高興你把它整理出來:)但應該指出,'Label'和'TextBlock'繼承自不同的基本控件,並使用不同的規則。一個'Label'繼承自'Control',它具有諸如尊重模板邊界的規則。 'TextBlock'繼承自'FrameworkElement',而不是。 – Rachel

回答

0

所以我意識到,對於標籤的缺省(串)模板是鋸齒狀的TextBlock(樣式繼承)

因爲我也被定義爲TextBlock的

<Style x:Key="TextBlockStyle" TargetType="TextBlock"> 
<Setter Property="Foreground" Value="{StaticResource ForegroundBrush}" /> 
<Setter Property="FontSize" Value="13.333" /> 
<Setter Property="FontFamily" Value="Segoe UI" /> 
<Style BasedOn="{StaticResource TextBlockStyle}" TargetType="{x:Type TextBlock}" /> 
全局樣式

無論有多少類型的標籤,我總是必須使用TextBlock的模板

因此,解決方案是定義一個虛擬TextBlock類

namespace Theme 
{ 
    public class HeaderTextBlock : TextBlock 
    { 
    } 
} 

然後分配給它自己的全球風格

xmlns:this="clr-namespace:Theme" 
<Style x:Key="HeaderTextBlockStyle" TargetType="this:HeaderTextBlock"> 
    <Setter Property="Foreground" Value="{StaticResource HeaderForegroundBrush}" /> 
    <Setter Property="FontSize" Value="13.333" /> 
    <Setter Property="FontFamily" Value="Segoe UI" /> 
</Style> 
<Style BasedOn="{StaticResource HeaderTextBlockStyle}" TargetType="{x:Type this:HeaderTextBlock}" /> 

而且使用的TextBlocks,而不是標籤(還沒有想出如何實現一個標籤的孩子卻因爲(標籤:TextBlock的)= FALSE

xmlns:theme="clr-namespace:Theme;assembly=Theme" 
<theme:HeaderTextBlock Text="Some text" Name="titleLabel" Style="{StaticResource HeaderTextBlockStyle}"/> 
+3

_「標籤是一個榮耀的TextBlock」_ - 完全沒有。 'Label'是一個'ContentControl',這意味着它能夠根據可用的模板呈現各種各樣的內容。是的,如果您的內容是「字符串」,則默認模板是「TextBlock」。但'Label'不僅僅是_「一個美化的TextBlock」_。 –

相關問題