Reputation: 16705
I'm using this as a basis to make an animation start using code behind. Based on the contents of the article, I have the following:
<Window.Resources>
<Storyboard x:Key="sbdLabelRotation">
<DoubleAnimation
Storyboard.TargetName="lblHello"
Storyboard.TargetProperty="(TextBlock.RenderTransform).(RotateTransform.Angle)"
From="0"
To="360"
Duration="0:0:0.5"
RepeatBehavior="4x" />
</Storyboard>
</Window.Resources>
I have the following XAML (obviously):
<Label x:Name="lblHello" Content="test" Margin="20"/>
And the code behind:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public void AnimateLabelRotation()
{
Storyboard sbdLabelRotation = (Storyboard)FindResource("sbdLabelRotation");
sbdLabelRotation.Begin(this);
}
Which I call from a button click event. The FindResource
works and finds the storyboard, but nothing happens. I have managed to get the animation to work on an event trigger, but clearly I'm missing something for the code behind.
Upvotes: 2
Views: 6318
Reputation: 3
There is a link to download the whole project http://www.galasoft.ch/mydotnet/articles/resources/article-2006102701/GalaSoftLb.Article2006102701.zip
You can study the code and see it running. Sometimes it's more helpful. Also in your code the part:
sbdLabelRotation.Begin(this);
could be wrong. As you know the this
keyword references the class itself, in your case the MainWindow
class. You should try without the this keyword.
Upvotes: 0
Reputation: 6289
This:
<Label x:Name="lblHello" Content="test" Margin="20"/>
and this:
Storyboard.TargetProperty="(TextBlock.RenderTransform).(RotateTransform.Angle)"
are not compatible.
When the animation tries to find the property to animate, it goes to (TextBlock.RenderTransform)
and finds null since you didn't declare it (actually it doesn't since you say TextBlock but apply it to Label, more on that later in the answer). Thus it cannot find .(RotateTransform.Angle)
.
To remedy the issue:
<Label x:Name="lblHello"
Content="test"
Margin="20"
RenderTransformOrigin="0.5,0.5">
<Label.RenderTransform>
<RotateTransform />
</Label.RenderTransform>
</Label>
Notice RenderTransformOrigin
setting - this means that the axis of rotation will be in the center of the object (X and Y).
Also, in the animation it should be:
Storyboard.TargetProperty="(Label.RenderTransform).(RotateTransform.Angle)"
Upvotes: 2