我有一个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();
}
在得到storyboard对象后,您可以使用storyboard的Children
属性访问double Animation
var storyBoard = this.Resources["RotateImage"] as Storyboard;
var rotateImageAnimation = (DoubleAnimation)storyBoard.Children[0];
请注意,使用children[0]
访问动画是最简单的,因为你的故事板很简单。