Welcome

首页 / 软件开发 / Silverlight / Silverlight:以编程方式使用动画

Silverlight:以编程方式使用动画2011-09-05 msdn Sailing有时您可能要动态(即时)更改动画的属性。例如,您可能要调整应用到对象 的动画行为,这取决于对象当前在布局中的位置、对象包含何种内容等等。可以 通过使用程序代码(例如 C# 或 Visual Basic)动态操作动画。

先决条件

您应熟悉 Silverlight 动画。有关简介,请参见动画概述。

通过名称访问动画

访问动画对象以更改其属性的最直接方法是:命名该动画对象,然后在代码中 通过该名称引用它。下面的示例包含一个 Ellipse,当您在屏幕上单击时它将显 示动画效果。为了实现此动画,在单击 Canvas 时,事件处理程序更改 PointAnimation 对象的 To 属性,然后启动动画。

运行此示例:http://go.microsoft.com/fwlink/? LinkId=139798&sref=change_animation_properties_1

XAML

<Canvas MouseLeftButtonDown="Handle_MouseDown"
Background="Gray" Width="600" Height="500">
<Canvas.Resources>
<Storyboard x:Name="myStoryboard">
<!-- The PointAnimation has a name so it can be accessed
from code. The To property is left out of the XAML
because the value of To is determined in code. -->
<PointAnimation
x:Name="myPointAnimation"
Storyboard.TargetProperty="Center"
Storyboard.TargetName="MyAnimatedEllipseGeometry"
Duration="0:0:2"/>
</Storyboard>
</Canvas.Resources>
<Path Fill="Blue">
<Path.Data>
<!-- Describes an ellipse. -->
<EllipseGeometry x:Name="MyAnimatedEllipseGeometry"
Center="200,100" RadiusX="15" RadiusY="15" />
</Path.Data>
</Path>
</Canvas>

VB

Private Sub Handle_MouseDown(ByVal sender As Object, ByVal e As MouseButtonEventArgs)
" Retrieve current mouse coordinates.
Dim newX As Double = e.GetPosition(Nothing).X
Dim newY As Double = e.GetPosition(Nothing).Y
Dim myPoint As Point = New Point
myPoint.X = newX
myPoint.Y = newY
myPointAnimation.To = myPoint
myStoryboard.Begin()
End Sub

C#

private void Handle_MouseDown(object sender, MouseButtonEventArgs e)
{
// Retrieve current mouse coordinates.
double newX = e.GetPosition(null).X;
double newY = e.GetPosition(null).Y;
Point myPoint = new Point();
myPoint.X = newX;
myPoint.Y = newY;
myPointAnimation.To = myPoint;
myStoryboard.Begin();
}