Difference between Style and ControlTemplate

In a style you set properties of a control.

<Style x:Key="MyButtonStyle" TargetType="Button">
    <Setter Property="Background" Value="Red"/>
</Style>

<Button Style="{StaticResource MyButtonStyle}"/>

All buttons that use this style will have their Backgrounds set to Red.

In a template you define the UI (structure) of the control.

<ControlTemplate x:Key="MyButtonTemplate" TargetType="Button">
    <Grid>
        <Rectangle Fill="Green"/>
        <ContentPresenter/>
    </Grid>
</ControlTemplate>

<Button Template="{StaticResource MyButtonTemplate}"/>

All buttons that use this template will have a green background that cannot be changed.

Values set in a template can only be replaced by replacing the entire template. Values in a style can be replaced by setting the value explicitly when using the control. That is why is better to use the properties of the control by using TemplateBinding instead of coding values.

<ControlTemplate x:Key="MyButtonTemplate" TargetType="Button">
    <Grid>
        <Rectangle Fill="{TemplateBinding Background}"/>
        <ContentPresenter/>
    </Grid>
</ControlTemplate>

Now the template uses the value of the Background property of the button it is applied to, so it can be customized:

<Button Template="{StaticResource MyButtonTemplate}" Background="Yellow"/>

Another useful feature is that controls can pick up a default style without having a specific style being assigned to them. You can’t do that with a template.

Just remove the x:Key attribute of the style (again: you can’t do this with templates). All buttons in the visual tree below the style will have this style applied.

Combining Templates and Styles is extra powerful: you can set the Template property in the style:

<Style TargetType="Button">
    <Setter Property="Background" Value="Red"/>
    <Setter Property="Template">
        <Setter.Value>
             <ControlTemplate TargetType="Button">
                 <Grid>
                     <Rectangle Fill="{TemplateBinding Background}"/>
                     <ContentPresenter/>
                 </Grid>
             </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)