Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Base a ControlTemplate on another ControlTemplate

I know there must be an easy answer to this but I can't find it.

I've got a button style called HoverButton.

<Style x:Key="HoverButton" TargetType="Button">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Border>
                    <ContentPresenter/>
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="BorderBrush" Value="Black"/>
                        <Setter Property="Background" Value="WhiteSmoke"/>
                        <Setter Property="Foreground" Value="DarkRed"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Setter Property="BorderBrush" Value="Transparent"/>
    <Setter Property="Background" Value="Transparent"/>
</Style>

I then want to create another 'derived' style that is based on a HoverButton with specific content. I've reduced the complexity of the above style here, but it's complex enough that I don't want to copy and paste it.

<Style x:Key="CloseButton" BasedOn="{StaticResource HoverButton}" TargetType="{x:Type Button}">
    <Setter Property="Content">
        <Setter.Value>
            <Path Width="8" Height="8" Stroke="{Binding Foreground, RelativeSource={RelativeSource FindAncestor, AncestorType=Button}}" Data="M0,0 L8,8 M8,0 L0,8" StrokeThickness="2" />
        </Setter.Value>
    </Setter>
</Style>

This doesn't work - "Specified element is already the logical child of another element. Disconnect it first." It seems like I need to redefine the Template property of the derived style, but somehow reference the base style's template.

Any ideas?

like image 648
Tim Rogers Avatar asked Sep 02 '11 14:09

Tim Rogers


1 Answers

You cannot base templates on one-another, but this error could easily be resolved. Just create an equivalent ContentTemplate instead of setting the Content. That way one Path is created for each button, and not one for all buttons (which is not allowed).

like image 64
H.B. Avatar answered Oct 23 '22 23:10

H.B.