How to reuse defined style in control template resources

4.3k Views Asked by At

I am new to WPF. I dont know how to do this.

I have this style defined -

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

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

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

</Style>

I have a control template -

<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

There are 2 best solutions below

3
sa_ddam213 On BEST ANSWER

If you want all Buttons in your ControlTemplate to use the Style just remove the x:Key from the style and add to the 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 with an x:Key will have to be declared on the control like Style="{StaticResource StandardButton}", to apply to all controls in the scope of the Resources you only have to declare the TargetType

If you already have a Style defined in your higher level Resources and you want to apply to all the Buttons in your ControlTemplate you can use the BasedOn property.

Example:

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

This will apply StandardButton Style to all Buttons in the scope of the Resources it was defined, in this case all the Buttons in the ExpanderTemplate

1
WannaCSharp On

You can reference your style using StaticResource and the key name of the Resource you defined

Style="{StaticResource StandardButton}"