访问UserControl资源中的元素

时间:2015-08-26 14:37:07

标签: c# wpf user-controls windows-phone-8.1 windows-phone

我有一个xaml文件,我用UserControl作为资源定义了storyboard

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

我想从后面的代码中访问RotateImageAnimation,但如果我写的话如下:

public void Foo(){
    RotateImageAnimation.To = 170;
}

我得到了一个运行时NullPointerException。如何访问资源中的元素?提前谢谢。

2 个答案:

答案 0 :(得分:3)

使用以下代码访问您的资源:

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

答案 1 :(得分:1)

添加llll的答案,获得故事板对象后,您可以使用故事板的Children属性访问双动画。

var storyBoard = this.Resources["RotateImage"] as Storyboard;
var rotateImageAnimation = (DoubleAnimation)storyBoard.Children[0];

请注意,使用children[0]访问动画是最简单的,因为您的故事板很简单。