Thursday, August 7, 2008

How to control an animation to be on/off at certain time

I find this useful when you want to catch your web user’s attention when they are browsing your website. Besides, animation can make your website look more lively and interactive.

In this section, I am not going to explain how to create an animation but how to control it to begin and stop in code behind using C#.

Before we go there, we need to create an animation in the first place and name it accordingly. You can create an animation easily using Expression Blend. You just have to click on the Add New Storyboard icon under the Objects and Timeline section and it will start recording. You may try to scale up and down an object or change its color. Let’s look at the following screenshot as an example:-

clip_image002

clip_image004

If you notice it, you may see the “Bip!” text coming out to represent ringing. So how do I set the animation begin time and stop time? The answer is “it depends on how you want it to be”.

Okay now, go to your Page.xaml.cs file.

  1. Create a Storyboard object and set it to null under Page class.
  2. Storyboard PhoneBip = null;



  3. Under the Public Page() constructor, instantiate a Storyboard object.


  4. PhoneBip = new Storyboard();



  5. PhoneBip object is a new object that does not have any animation set. So now I want to reference it to the one that I have already created in XAML.


  6. PhoneBip = (Storyboard)base.FindName("PhoneRing");



  7. I also want to set its behavior to Stop once it has finished the animation.


  8. PhoneBip.FillBehavior = FillBehavior.Stop;



  9. You have done the necessary set-up, you may try to begin the animation.


  10. PhoneBip.Begin();



  11. You may want to start the animation at certain time, then you can use DispatcherTimer object to control the tick count.



Below is the sample code:-



public partial class Page : UserControl
{
Storyboard PhoneBip = null;
DispatcherTimer t = null;
private static int tickCount = 0;

public Page()
{
InitializeComponent();

PhoneBip = new Storyboard();
PhoneBip = (Storyboard)base.FindName("PhoneRing");
PhoneBip.FillBehavior = FillBehavior.Stop;

t = new DispatcherTimer();
t.Interval = TimeSpan.Zero;
t.Tick += new EventHandler(t_Tick);
t.Start();

}

protected void t_Tick(object sender, EventArgs e)
{
tickCount += 1;
this.Update();
}

private void Update()
{

if (tickCount > 300)
{
PhoneBip.Begin();
tickCount = 0;

}
}

No comments: