locked
XAML/C# dev: Cannot get clock updated in an application

    Question

  • Hi all,

    I am very new to windows 8 development, for my background. So, I start myself with a very simple project - a clock application that syncs with local time.

    I am using DateTime t = DateTime.now() to show the clock in my app. However, the clock is not updating automatically. It freezes at the current time when I open the app.

    I am putting my code inside MainPage.xaml.cs.  I cant get it running by putting infinite loop of while(true){} either. Are there any ways to make the clock running inside the app?

    Tuesday, March 11, 2014 10:55 AM

Answers

  • You can use a DispatcherTimer for this.

    For this XAML ...

    <TextBlock x:Name="Clock" />

    ... you can use this C# to regularly update:

    public MainPage()
    {
        this.InitializeComponent();
    
        DispatcherTimer timer = new DispatcherTimer();
        timer.Interval = TimeSpan.FromSeconds(1);
        timer.Tick += this.Timer_Tick;
        timer.Start();
    }
    
    private void Timer_Tick(object sender, object e)
    {
        this.Clock.Text = string.Format("{0:hh:mm:ss}", DateTime.Now);
    }

    • Marked as answer by Aero Techno Tuesday, March 11, 2014 12:10 PM
    Tuesday, March 11, 2014 11:53 AM

All replies

  • You can use a DispatcherTimer for this.

    For this XAML ...

    <TextBlock x:Name="Clock" />

    ... you can use this C# to regularly update:

    public MainPage()
    {
        this.InitializeComponent();
    
        DispatcherTimer timer = new DispatcherTimer();
        timer.Interval = TimeSpan.FromSeconds(1);
        timer.Tick += this.Timer_Tick;
        timer.Start();
    }
    
    private void Timer_Tick(object sender, object e)
    {
        this.Clock.Text = string.Format("{0:hh:mm:ss}", DateTime.Now);
    }

    • Marked as answer by Aero Techno Tuesday, March 11, 2014 12:10 PM
    Tuesday, March 11, 2014 11:53 AM
  • Thanks a bunch! That works
    Tuesday, March 11, 2014 12:10 PM