WPF Analog Clock

Download WPFClock.zip (6 KB)

In this post I’ve included the full source for an analog Silverlight clock. Having only recently started to learn WPF, I am still very much a beginner but I’m offering this as a simple example for beginners to learn from.

I won’t describe the XAML here as its pretty cumbersome however the javascript by contrast is rather light… we start with some declarations:

// We use this to get a handle on the XAML controls
var globalRootElement;

// Create a clock object
if (!window.Clock)
	Clock = {};

// Create the Clock.Page function
Clock.Page = function()
{
}

Next we create the function prototype:

Clock.Page.prototype =
{
  // Constructor
  handleLoad: function(control, userContext, rootElement)
  {
    this.control = control;

    // So we don't have to pass refs
    globalRootElement = rootElement;

    // Set initial second hand position
    var date = new Date();
    var secHand = globalRootElement.findName("secondHand");
    var secHandRT = secHand.RenderTransform.Children.getItem(2);
    secHandRT.Angle = (360 / 60) * date.getSeconds() - 90;
    var secondAnimAngle = globalRootElement.findName("secondAnimAngle");
    secondAnimAngle.Value = secHandRT.Angle;

    // Draw initial clock face
    updateClock();

    // Periodically update clock every second (1000 ms)
    setInterval("updateClock();", 1000);
  }
}

Finally, create the ‘updateClock’ method to calculate and draw the hand positions:

// Updates the hand positions using the local system time
function updateClock()
{
  var date = new Date();

  // Set second hand
  var secondAnim = globalRootElement.findName("secondAnim");
  var secondAnimAngle = globalRootElement.findName("secondAnimAngle");
  secondAnimAngle.Value += 6;
  secondAnim.Begin();

  // Set minute hand
  var minHand = globalRootElement.findName("minuteHand");
  var minHandRT = minHand.RenderTransform.Children.getItem(2);
  minHandRT.Angle = (360 / 60) * date.getMinutes() - 90;

  // Set hour hand
  var hrHand = globalRootElement.findName("hourHand");
  var hrHandRT = hrHand.RenderTransform.Children.getItem(2);
  hrHandRT.Angle = (360 / 12) * date.getHours() - 90;
  hrHandRT.Angle += (360 / 12) * (date.getMinutes() / 60);
}

That’s it! The full source can be downloaded below:

Download WPFClock.zip (6 KB)

Advertisements
This entry was posted in Projects and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s