2013-02-18 32 views
2

我是WPF的新手。我不知道如何做到這一點。如何在控件模板資源中重用定義的樣式

我有這個樣式定義 -

<Style TargetType="{x:Type Button}" x:Key="StandardButton"> 

<Setter Property="Background" Value="{StaticResource LightBackground}"/> 

    <Setter Property="Foreground" Value="{StaticResource Foreground}"/> 

</Style> 

我有一個控制模板 -

<ControlTemplate x:Key="ExpanderTemplate" TargetType="{x:Type Expander}"> 

<ControlTemplate.Resources> 

     <Style TargetType="{x:Type Button}" /* Here I need to put above defined style */></Style> 

    </ControlTemplate.Resources> 

</ControlTemplate> 

回答

1

如果您想要ControlTemplate中的所有Buttons使用Style剛剛從風格刪除x:Key並添加到ControlTemplate.Resources

<ControlTemplate.Resources> 
    <Style TargetType="{x:Type Button}"> 
     <Setter Property="Background" Value="{StaticResource LightBackground}"/> 
     <Setter Property="Foreground" Value="{StaticResource Foreground}"/> 
    </Style> 
</ControlTemplate.Resources> 

Stylesx:Key會對像Style="{StaticResource StandardButton}"控制中聲明,適用於所有控件的Resources你只需要範圍聲明TargetType

如果你已經在你的更高水平Resources定義的Style,並要適用於所有的ButtonsControlTemplate可以使用BasedOn prope RTY。

實施例:

<ControlTemplate x:Key="ExpanderTemplate" TargetType="{x:Type Expander}"> 
    <ControlTemplate.Resources> 
     <Style TargetType="{x:Type Button}" BasedOn="{StaticResource StandardButton}" /> 
    </ControlTemplate.Resources> 
</ControlTemplate> 

這將在ExpanderTemplate

+0

我可以做到這一點,但我有很多其他控件來引用此按鈕樣式。我還舉了一個例子。風格有很多代碼,我不能把它作爲每個控件的資源。我想在資源目錄 – user2039445 2013-02-18 07:15:58

+0

中的任何地方引用它,所以你想要所有的按鈕都有這種風格? – 2013-02-18 07:18:11

+0

更新了我認爲你正在尋找的答案。 – 2013-02-18 07:29:45

0

可以使用靜態資源和資源的您定義

Style="{StaticResource StandardButton}" 
鍵名稱引用您的風格
+0

我需要在擴展所有的按鈕應用StandardButtonStyleResources的範圍內的所有按鈕它被定義,在這種情況下,所有Buttons必須是這種風格。樣式不具有稱爲樣式FYI的屬性。 – user2039445 2013-02-18 06:49:10

相關問題