我正在Windows Phone 8 SDK中开发游戏,我需要一个倒数计时器。
我第一次实现了Dispatcher计时器,请点击CLICK计时器减少且没有错误!
但是,如果我按RESET(应该将其重置为60秒并开始倒数),它将重置为60但它每秒减少“ 2秒”!
如果我再按一次RESET,它每秒减少3秒
我以与我的应用相同的想法编写的示例代码:(以及相同的错误结果)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using PhoneApp3.Resources;
using System.Windows.Threading;
namespace PhoneApp3
{
public partial class MainPage : PhoneApplicationPage
{
private DispatcherTimer time = new DispatcherTimer(); // DISPATCHER TIMER
private int left;
// Constructor
public MainPage()
{
InitializeComponent();
}
//Starting Countdown
private void Start_Click_1(object sender, RoutedEventArgs e)
{
left = 60; // time left
time.Interval = TimeSpan.FromSeconds(1);
time.Tick += time_Tick;
time.Start();
}
void time_Tick(object sender, EventArgs e)
{
left--; // decrease
txt.Text = Convert.ToString(left); // update text
}
private void reset_Click(object sender, RoutedEventArgs e)
{
time.Stop();
Start_Click_1(null, null); // RE - START
}
}
}
每次按reset并Start_Click_1
再次运行时,您都在time_Tick
再次订阅:
time.Tick += time_Tick;
因此,在按下Reset 3次后,您被订阅3次,并且每次tick事件触发时,下面的代码行均运行3次:
left--;
将订阅移到构造函数中:
public MainPage()
{
InitializeComponent();
time.Tick += time_Tick;
}
//Starting Countdown
private void Start_Click_1(object sender, RoutedEventArgs e)
{
left = 60; // time left
time.Interval = TimeSpan.FromSeconds(1);
time.Start();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句