如何在控件模板资源中重用已定义的样式

时间:2013-02-18 06:44:32

标签: c# wpf controltemplates

我是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>

2 个答案:

答案 0 :(得分:1)

如果您希望Buttons中的所有ControlTemplate使用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>
Styles的{​​{1}}必须在控件上声明x:Key,以便应用Style="{StaticResource StandardButton}"范围内的所有控件,您只需要声明Resources

如果您已经在更高级TargetType中定义了Style并且想要申请Resources中的所有Buttons,则可以使用{{1}属性。

示例:

ControlTemplate

这会将BasedOn <ControlTemplate x:Key="ExpanderTemplate" TargetType="{x:Type Expander}"> <ControlTemplate.Resources> <Style TargetType="{x:Type Button}" BasedOn="{StaticResource StandardButton}" /> </ControlTemplate.Resources> </ControlTemplate> 应用于定义的StandardButton范围内的所有按钮,在这种情况下Style中的所有Resources

答案 1 :(得分:0)

您可以使用StaticResource和您定义的资源的密钥名称来引用您的样式

Style="{StaticResource StandardButton}"
相关问题