【问题标题】:How to reuse defined style in control template resources如何在控件模板资源中重用定义的样式
【发布时间】:2013-02-18 06:44:32
【问题描述】:

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

【问题讨论】:

    标签: c# wpf controltemplates


    【解决方案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,并且您想应用于ControlTemplate 中的所有Buttons,您可以使用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 范围内的所有按钮,在本例中为ExpanderTemplate 中的所有Buttons

    【讨论】:

    • 我可以这样做,但是我有很多其他控件可以引用此按钮样式。我也只是举了一个例子。样式有很多代码,我不能把它作为资源放在每个控件中。我想在 resourceDirectory 中到处引用它
    • 所以您希望所有按钮都具有这种样式?
    • 更新了我认为您正在寻找的答案。
    【解决方案2】:

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

    Style="{StaticResource StandardButton}"
    

    【讨论】:

    • 我需要Expander中的所有按钮都必须是这种样式。 Style 没有名为 Style FYI 的属性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多