Reputation: 23
I want to animate the width of a control(the Rectangle here). This code does animate the width and auto revereses the width back to its original but not if i trigger the animation again midway. In that case the width auto reverses to the width when I retriggered it, never going back to its original width.
And giving the animation a "From" property requires me to remember the original width and it is not runtime width, it just stays being that. Cant find a way to bind to the Rectangle width or something.
Like saying <DoubleAnimation From="rectangle.Width"/>
<Style x:Key="animation" TargetType="ContentControl">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Grid>
<Rectangle x:Name="rectangle" Fill="Blue" Width="500"></Rectangle>
</Grid>
<ControlTemplate.Triggers>
<EventTrigger RoutedEvent="MouseDown">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetName="rectangle" Storyboard.TargetProperty="Width"
To="250" Duration="0:0:1" AutoReverse="True"></DoubleAnimation>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
I think binding the rectangle element width to the the "From" property in the animation will solve all the problem. Because it will always auto reverse back to that.
Acually I tried From="{Binding ElementName=rectangle,Path=Width}"
. its a valid xaml code. But after build errors it says
Error Cannot freeze this Storyboard timeline tree for use across threads.
Upvotes: 0
Views: 875
Reputation: 128013
Instead of animation the Rectangle's Width and hence deal with absolute size values, you may better animate a ScaleTransform, e.g. like this:
<ControlTemplate>
<Grid>
<Rectangle x:Name="rectangle" Fill="Blue" Width="500"
RenderTransformOrigin="0.5,0.5">
<Rectangle.RenderTransform>
<ScaleTransform/>
</Rectangle.RenderTransform>
</Rectangle>
</Grid>
<ControlTemplate.Triggers>
<EventTrigger RoutedEvent="MouseDown">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation
Storyboard.TargetName="rectangle"
Storyboard.TargetProperty="RenderTransform.ScaleX"
From="1" To="0.5" Duration="0:0:1" AutoReverse="True"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
Upvotes: 1