Reputation: 12972
I have a xaml file where I defined a UserControl
with a storyboard
as a resource this way:
<UserControl.Resources>
<Storyboard x:Key="RotateImage">
<DoubleAnimation x:Name="RotateImageAnimation" From="0" To="360" RepeatBehavior="Forever" Duration="00:00:00.5" Storyboard.TargetName="rotateTransform" Storyboard.TargetProperty="Angle"/>
</Storyboard>
</UserControl.Resources>
I'd like to access the RotateImageAnimation from the code behind, but if I write something like:
public void Foo(){
RotateImageAnimation.To = 170;
}
I get a runtime NullPointerException
. How can I access the element within the resource? Thank you in advance.
Upvotes: 1
Views: 1817
Reputation: 10865
Access your resources using the following code:
public void Foo(){
var storyBoard = this.Resources["RotateImage"] as Storyboard;
// Get the storboard's value to get the DoubleAnimation and manipulate it.
var rotateImageAnimation = (DoubleAnimation)storyBoard.Children.FirstOrDefault();
}
Upvotes: 3
Reputation: 842
Adding on llll's Answer, After you got the storyboard object, you can access the double Animation using storyboard's Children
property.
var storyBoard = this.Resources["RotateImage"] as Storyboard;
var rotateImageAnimation = (DoubleAnimation)storyBoard.Children[0];
Please note accessing the animation using children[0]
is the easiest as your storyboard is simple.
Upvotes: 1