A Simple Animation in Code

image_pdfimage_print


   
  

<Window x:Class="WpfApplication1.SimpleAnimation" 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        Title="Simple Animation Example" Height="300" Width="300"> 
    <Canvas>
        <Rectangle x:Name="rect1" Width="100" Height="50" Fill="Blue"/> 
    </Canvas> 
</Window> 
//File:Window.xaml.cs

using System; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Media; 
using System.Windows.Shapes; 
using System.Windows.Media.Animation; 


namespace WpfApplication1 
{ 
    public partial class SimpleAnimation : Window 
    { 
        public SimpleAnimation() 
        { 
            InitializeComponent(); 
            DoubleAnimation da = new DoubleAnimation(); 
            da.From = 0; 
            da.To = 200; 
            da.Duration = TimeSpan.FromSeconds(5); 
            da.AutoReverse = true; 
            da.RepeatBehavior = RepeatBehavior.Forever; 
            rect1.BeginAnimation(Canvas.LeftProperty, da); 
            rect1.BeginAnimation(Canvas.TopProperty, da); 
        } 
    } 
}