访问 UserControl 资源中的元素

Accessing an element inside a UserControl resource

我有一个 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。如何访问资源中的元素?提前谢谢你。

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

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

补充llll的回答,得到storyboard对象后,可以使用storyboard的Children访问双动画 属性.

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

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