How to schedule a repeating task to count down a number in windows phone 8

二次信任 提交于 2019-12-20 05:14:11

问题


I need to just have a simple task that runs as long as the user is on one specific screen. On this screen there is a count down timer.

I looked into Background Agents - but that seems not to be the right approach.

Basically it should work like this: The user goes to this one screen, presses start and the cont down timer starts to count down - every 30 seconds update is perfectly ok.

How should I do this on WP8 ? Many thanks!


回答1:


You should use a DispatcherTimer as wkempf points out. Pretty simple to create actually. Something like this (where you have a TextBlock named countText in your xaml:

public partial class MainPage : PhoneApplicationPage
{
    private DispatcherTimer _timer;
    private int _countdown;

    // Constructor
    public MainPage()
    {
        InitializeComponent();

        _countdown = 100;
        _timer = new DispatcherTimer();
        _timer.Interval = TimeSpan.FromSeconds(1);
        _timer.Tick += (s, e) => Tick();
        _timer.Start();
    }

    private void Tick()
    {
        _countdown--;

        if (_countdown == 0)
        {
            _timer.Stop();
        }

        countText.Text = _countdown.ToString();
    }
}



回答2:


There are numerous Timers in .NET. System.Windows.Threading.DispatcherTimer is probably what you want, but System.Threading.Timer might be what you want as well. Depend on whether you want to run the periodic code in the background or on the UI thread.



来源:https://stackoverflow.com/questions/13874981/how-to-schedule-a-repeating-task-to-count-down-a-number-in-windows-phone-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!