Showing posts with label digital Clock.. Show all posts
Showing posts with label digital Clock.. Show all posts

Wednesday, April 25, 2012

Simplified Digital Clock for Silverlight

Another personal note to help me remember how to create a very simple digital clock in Silverlight. Posted if other people are working on a simple clock and don't want to write a lot of code.

Got most of the code from this CodeProject Post.

This is creating a very simple clock display using TextBlocks.

There are four TextBlocks - each are named
1. ClockDay
2. ClockMonth
3.ClockYear
4. ClockTime

In order for the required commands to work, you need the following statements at the very top of the C# codebehind:

using System.Windows.Input;
using System.Threading;
using System.Windows.Media;
using System.Windows.Threading;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

Once those are called, then just setting up the actual codebehind

namespace MyClockApp
{
   public partial class MyDigitalClockDisplay : UserControl
   {
      public MyDigitalClockDisplay()
      {
         InitializeComponent();

         this.LayoutRoot.DataContext = this; // I had other items with bindings on this control

        StartTimer()
      }
   
   private void StartTimer()
   {
      DispatcherTimer myDispatcherTimer = new DispatcherTimer()
      myDispatcherTimer.Interval = new TimerSpan(0,0,1);
      myDispatcherTimer.Tick += new EventHandler(Each_Tick);
      myDispatcherTimer.Start();
    }

   private void Each_Tick(object sender, EventArgs e)
   {

     // A listing of the different string formats for the DateTime are defined on this Microsoft Page.
      ClockDay.Text = DateTime.Now.ToString("dd");
      ClockMonth.Text = DateTime.Now.ToString("MMMM");
     ClockYear.Text = DateTime.Now.ToString("yyyy");
      ClockTime.Text = DateTime.Now.ToString("hh:mm:ss");
}
}
}


Below is an image showing the layout I used and which TextBlock was used for each of the values.