Five Ways to Animate In Silverlight

Oh this is so good: Five Ways to Animate In Silverlight

I’m copying down to preserve it:

Using Storyboard.Begin

// Animate the canvas left property
DoubleAnimation daLeft = new DoubleAnimation();
daLeft.To = 200.0;
daLeft.Duration = new Duration(new TimeSpan(0, 0, 0, 1));

// Set the storyboard target and target property
Storyboard.SetTarget(daLeft, MyRectangle);
Storyboard.SetTargetProperty(daLeft, new PropertyPath(Canvas.LeftProperty));

// Add the animation to the storyboard and start it
Storyboard st = new Storyboard();
st.Children.Add(daLeft);
st.Begin();

Using an empty Storyboard as a timer:

Storyboard emptyStoryboard = new Storyboard();

public MainPage() {
    InitializeComponent();

    emptyStoryboard.Duration = TimeSpan.FromMilliseconds(0);
    emptyStoryboard.Completed += new EventHandler(AnimateRectangle);
    emptyStoryboard.Begin();
}

void AnimateRectangle(object sender, EventArgs e) {
    // Animate the canvas left property
    MyRectangle.SetValue(Canvas.LeftProperty,
      (double)MyRectangle.GetValue(Canvas.LeftProperty) + 1.0);

    if ((double)MyRectangle.GetValue(Canvas.LeftProperty) > 200.0)
        emptyStoryboard.Stop();
    else
        emptyStoryboard.Begin();
}

3. Using System.Windows.Media.CompositionTarget.Rendering

public MainPage() {
    InitializeComponent();

    CompositionTarget.Rendering += new EventHandler(AnimateRectangle);
}

void AnimateRectangle(object sender, EventArgs e) {
     // Animate the canvas left property
    MyRectangle.SetValue(Canvas.LeftProperty,
       (double)MyRectangle.GetValue(Canvas.LeftProperty) + 1.0);

    if ((double)MyRectangle.GetValue(Canvas.LeftProperty) > 200.0)
        MyRectangle.SetValue(Canvas.LeftProperty, 200.0);
}

Using System.Windows.Threading.DispatcherTimer

private DispatcherTimer Timer = new DispatcherTimer();

public MainPage() {
    InitializeComponent();

    Timer.Interval = TimeSpan.Zero;
    Timer.Tick += new EventHandler(AnimateRectangle);
    Timer.Start();
}

void AnimateRectangle(object sender, EventArgs e) {
    // Animate the canvas left property, this is UI-thread safe
    MyRectangle.SetValue(Canvas.LeftProperty,
        (double)MyRectangle.GetValue(Canvas.LeftProperty) + 1.0);

    if ((double)MyRectangle.GetValue(Canvas.LeftProperty) > 200.0)
        Timer.Stop();
}

Using System.Threading.Timer

Timer Timer = null;

public MainPage() {
    InitializeComponent();
     Timer = new Timer(Animate, null, 0, 1);
}

void Animate(object state) {
     // This is required because the Animate method is called on a different thread than the UI
    Dispatcher.BeginInvoke(new Action(AnimateRectangle));
}

void AnimateRectangle() {
     // Animate the canvas left property
    MyRectangle.SetValue(Canvas.LeftProperty,
               (double)MyRectangle.GetValue(Canvas.LeftProperty) + 1.0);

    if ((double)MyRectangle.GetValue(Canvas.LeftProperty) > 200.0)
        Timer.Dispose();
}

About this entry