2010-01-03 58 views

回答

5

使用下面的XAML:

<UserControl x:Class="SilverlightApplication1.MainPage" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 
    <Canvas x:Name="LayoutRoot"> 
    <Rectangle x:Name="myBox" Fill="Red" Height="100" Width="100" Canvas.Left="0" Canvas.Top="0" /> 
    </Canvas> 
</UserControl> 

你可以創建動畫編程方式使用這樣的:

public partial class MainPage : UserControl 
{ 
    public MainPage() 
    { 
     InitializeComponent(); 

     Loaded += MainPage_Loaded; 
    } 

    void MainPage_Loaded(object sender, RoutedEventArgs e) 
    { 
     var moveAnimation = CreateAnimation(this.myBox); 
     moveAnimation.Begin(); 
    } 

    public Storyboard CreateAnimation(FrameworkElement element) 
    { 
     var storyboard = new Storyboard(); 

     var downAnimation = new DoubleAnimationUsingKeyFrames(); 
     Storyboard.SetTarget(downAnimation, element); 
     Storyboard.SetTargetProperty(downAnimation, new PropertyPath(Canvas.TopProperty)); 
     downAnimation.KeyFrames.Add(new EasingDoubleKeyFrame 
     { 
      KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(2)), 
      Value = 200 
     }); 
     storyboard.Children.Add(downAnimation); 

     var overAnimation = new DoubleAnimationUsingKeyFrames(); 
     Storyboard.SetTarget(overAnimation, element); 
     Storyboard.SetTargetProperty(overAnimation, new PropertyPath(Canvas.LeftProperty)); 
     overAnimation.KeyFrames.Add(new EasingDoubleKeyFrame 
     { 
      KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(2)), 
      Value = 0 
     }); 
     overAnimation.KeyFrames.Add(new EasingDoubleKeyFrame 
     { 
      KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(4)), 
      Value = 200 
     }); 
     storyboard.Children.Add(overAnimation); 


     return storyboard; 
    } 
}