2014-08-30 53 views
3

我創建了一個名爲baseStyle風格類似這樣的基礎:出現InvalidOperationException:只能在與目標類型風格是基本類型「的TextBlock」

<Style TargetType="{x:Type Control}" x:Key="baseStyle"> 
    <Setter Property="FontSize" Value="30" /> 
    <Setter Property="FontFamily" Value="Saumil_guj2" /> 
</Style> 

然後我用它像一個ListBoxItem的:

<Style TargetType="{x:Type ListBoxItem}" BasedOn="{StaticResource baseStyle}"> 

</Style> 

它很高興地接受baseStyleFontSizeFontFamily

我試圖做類似的事情的TextBlock:

​​

現在它的抱怨。我的意思是它給了我免除︰

InvalidOperationException: Can only base on a Style with target type 
that is base type 'TextBlock'. 

所以,我檢查了MSDN。

那裏我發現ListBoxItem間接從System.Windows.Controls派生。它可以找到here

那裏我還發現TextBlock也從System.Windows.Controls派生。它可以被發現here

所以,我不明白爲什麼我得到這個錯誤?

+2

創建樣式'TextBlock'不從'Control'而是直接從'FrameworkElement'派生。 'TextBlock'和'Control'之間沒有共同的類,它具有'FontSize'和'FontFamily'。他們都分開實施它 – dkozl 2014-08-30 19:52:36

+1

@dkozl你應該作出回答。 – 2014-08-30 19:55:29

回答

11

正如在評論TextBlock中提到的並非來自Control而是直接從FrameworkElementTextBlockControl之間沒有共同等級,其具有FontSizeFontFamily。他們都單獨實施。你可以做它FrameworkElement排字附加屬性TextElement.FontSizeTextElement.FontFamily

<Style TargetType="{x:Type FrameworkElement}" x:Key="baseStyle"> 
    <Setter Property="TextElement.FontSize" Value="30" /> 
    <Setter Property="TextElement.FontFamily" Value="Saumil_guj2" /> 
</Style> 
<Style TargetType="{x:Type ListBoxItem}" BasedOn="{StaticResource baseStyle}"> 

</Style> 
<Style TargetType="{x:Type TextBlock}" BasedOn="{StaticResource baseStyle}"> 

</Style> 
+1

謝謝@dkozl。這是完美的。我在發佈這個問題後發佈了FrameworkElement,並且因爲它不包含FontSize和FontFamily而出現另一個錯誤。現在我學到了新的教訓。在這種情況下,我應該使用TextElement.FontSize。再一次感謝你。 – Vishal 2014-08-30 20:32:34