Did You Know… That You Can Create A Timer Using XAML Animation?

To do so, create a Storyboard and mark that you will handle the Completed event.

<Storyboard Completed="OnTimerCompleted">

Put in the simplest Animation you can manage (name it, so that you can set the duration programmatically).

<DoubleAnimation x:Name="TimerDuration"

make sure you give it a duration, and point it at the simplest object you can create.

Duration="00:00:01.00" 
Storyboard.TargetName="MyRect"
Storyboard.TargetProperty="Height"

When the duration expires you can take action and, if you wish, reset the timer.

function OnTimerCompleted…

Here's a complete sample…

<Canvas xmlns="http://schemas.microsoft.com/client/2007" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    
    <Canvas.Resources>
        <Storyboard 
            x:Name="myTimer" 
            Completed="OnTimerCompleted">
            <DoubleAnimation x:Name="TimerDuration"
                Duration="00:00:01.00" 
                Storyboard.TargetName="MyRect"
                Storyboard.TargetProperty="Height" />
        </Storyboard>
    </Canvas.Resources>

    <Canvas>
        <Rectangle x:Name="MyRect"/>
    </Canvas>

</Canvas>

Here's the javascript…

MyDemo.Scene.prototype =
{
    handleLoad: function(plugIn, userContext, rootElement) 
    {
        // set the timer duration
        timer = plugIn.content.findName("TimerDuration"); 
        timer.Duration="00:00:05.00";
        
        // start the timer
        myStoryboard = plugIn.content.findName("myTimer"); 
        myStoryboard.begin();
    }
}

function OnTimerCompleted(sender, args)
{
       alert ("Timer completed!");
       myStoryboard = sender.findName("myTimer");
       myStoryboard.begin();  //restart timer
}

About Jesse Liberty

Jesse Liberty is an independent consultant and programmer with three decades of experience writing and delivering software projects. He is the author of 2 dozen books and multiple Pluralsight courses, and has been a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Xamarin Certified Mobile Developer and a Xamarin MVP, Microsoft MVP and Telerik MVP.
This entry was posted in z Silverlight Archives and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *