tags:

views:

15

answers:

1

I'm creating a ControlTemplate for a Button. I want to animate the size so it grows to fit the content when the mouse hovers over it. However, I'm not sure how to get the content size in the triggers section. Here is what I have.

<ControlTemplate x:Key="buttonTemplate" TargetType="Button">
<Grid Name="grid" Height="12" Width="12" Opacity="0.4">
<ContentPresenter Name="content" ... />
</Grid>

<ControlTemplate.Triggers>
    <EventTrigger RoutedEvent="MouseEnter">
        <BeginStoryboard>
            <Storyboard>
        <DoubleAnimation
            Storyboard.TargetName="grid"
            Storyboard.TargetProperty="Width"
            To="40"                         
            Duration="0:0:0.4"/>    
        <DoubleAnimation
            Storyboard.TargetName="grid"
                Storyboard.TargetProperty="Height"
            To="20"                         
            Duration="0:0:0.4"/>    
        </Storyboard>
    </BeginStoryboard>
    </EventTrigger>

    <EventTrigger RoutedEvent="MouseLeave">
    <BeginStoryboard>
        <Storyboard>
            <DoubleAnimation
            Storyboard.TargetName="grid"
            Storyboard.TargetProperty="Width"
            Duration="0:0:0.2"/>    
        <DoubleAnimation
            Storyboard.TargetName="grid"
            Storyboard.TargetProperty="Height"
            Duration="0:0:0.2"/>                        
        </Storyboard>
    </BeginStoryboard>
    </EventTrigger>

</ControlTemplate.Triggers>
</ControlTemplate>

I've tried using TemplateBinding in place of the To="40" in the trigger, but that causes exceptions. How can I use dynamic values in the triggers?

A: 

Rather than animating the layout sizes directly you can apply a ScaleTransform to grid and animate its ScaleX and ScaleY values. This will not only adjust automatically for whatever the size is but can also provide better performance, especially if you apply it as a RenderTransform instead of a LayoutTransform. If there are other changes to the layout that you're expecting to happen during the animation you can stick with LayoutTransform but it will be slower as it needs to continually recalculate layout measurements and arrangement.

John Bowen
If I use ScaleTransform, won't I have the same problem? I don't know how to get the max/min size from the content of the Button.
TheSean
No. You're currently trying to animate layout units. ScaleTransform sizes by percentage so to animate to full size use To="1".
John Bowen