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?
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.