How to display a clock with the current time in a

2019-02-26 21:04发布

I am trying to create an Windows 10 IoT app running headless on a Raspberry Pi 2. Everything is set up correctly and I am able to debug my from Visual Studio using the Raspberry Pi as the remote machine for debugging.

Now I want to add a clock on the app page but I can't figure out how to keep the displayed time updated. In plain old C# I would use a BackgroudWorker or something similar to keep the displayed time current, but that type is not available in UWP.

I have been looking into "Create and register a background task" on MSDN but that seems to be way to complex, just to be able to keep the display time up to date.

So my question is: How can I - in the simplest posible way - create a clock display that is updated every time the time ticks?

1条回答
混吃等死
2楼-- · 2019-02-26 21:36

If your app is running headless, you will have to set data to a display device (LCD, LEDs, etc.). With a headed app, you will use a XAML page to display the clock. You can use a timer to get notified every time span occurs.

Timer declaration

ThreadPoolTimer _clockTimer = null;

Timer initialization

_clockTimer = ThreadPoolTimer.CreatePeriodicTimer(_clockTimer_Tick, TimeSpan.FromMilliseconds(1000));

Timer tick event

private void _clockTimer_Tick(ThreadPoolTimer timer)
{
    //Update your display. Use a dispatcher if needed
}

ThreadPoolTimer reference documentation

https://msdn.microsoft.com/en-us/library/windows/apps/xaml/windows.system.threading.threadpooltimer.aspx

Keep in mind that a Raspberry Pi does not have a battery to save the current time. Your board will have to sync through the Internet to update its date/time.

查看更多
登录 后发表回答