Search code examples
c#wpfuser-controlswindows-phone-8.1windows-phone

Accessing an element inside a UserControl resource


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.


Solution

  • 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();
    }