Silverlight 代码创建动画 原创示例

代码中使用了 C# 3.0 语法

效果是一个红色矩形从右下角移动到左上角

仅仅是示例,演示如何在代码中动态创建动画

 

MainPage.xaml
   
     
< UserControl x:Class ="Hongcing.Silverlight.Create_And_Run_Animation"
xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml" >
< Canvas Loaded ="LayoutRoot_Loaded" />
</ UserControl >

 

MainPage.xaml.cs
   
     
1 using System;
2   using System.Windows;
3   using System.Windows.Controls;
4   using System.Windows.Media;
5 using System.Windows.Media.Animation;
6 using System.Windows.Shapes;
7
8 namespace Hongcing.Silverlight
9 {
10 public partial class Create_And_Run_Animation : UserControl
11 {
12 public Create_And_Run_Animation()
13 {
14 InitializeComponent();
15 }
16
17 private void LayoutRoot_Loaded( object sender, RoutedEventArgs e)
18 {
19 var redRectangle = new Rectangle
20 {
21 Width = 300 ,
22 Height = 200 ,
23 Fill = new SolidColorBrush(Colors.Red),
24 Stroke = new SolidColorBrush(Colors.Black)
25 };
26
27 (sender as Panel).Children.Add(redRectangle);
28
29 var leftAnimation = new DoubleAnimation
30 {
31 Duration = new Duration(TimeSpan.FromSeconds( 5 )),
32 From = 700 ,
33 To = 0
34 };
35
36 var topAnimation = new DoubleAnimation
37 {
38 Duration = leftAnimation.Duration,
39 From = 350 ,
40 To = 0
41 };
42
43 Storyboard.SetTarget(leftAnimation, redRectangle);
44 Storyboard.SetTarget(topAnimation, redRectangle);
45
46 // 属性路径也可以用 new PropertyPath("(Canvas.Left)")、new PropertyPath("(Canvas.Top)")
47 Storyboard.SetTargetProperty(leftAnimation, new PropertyPath(Canvas.LeftProperty));
48 Storyboard.SetTargetProperty(topAnimation, new PropertyPath(Canvas.TopProperty));
49
50 // 此处没有添加到资源中,而是直接启动动画。
51 new Storyboard { Children = { leftAnimation, topAnimation } }.Begin();
52 }
53 }
54 }
55

 

你可能感兴趣的:(silverlight)