我在windows phone中有这样的代码
private void btnrun_Click(object sender, RoutedEventArgs e)
{
t = 0;
Start_timer();
}
public void Start_timer()
{
timer2 = new DispatcherTimer();
timer2.Tick += timer_Tick2;
timer2.Interval = new TimeSpan(0, 0, 0, 0, 1000);
timer2.Start();
}
void timer_Tick2(object sender, object e)
{
t++;
txttime.Text = t.ToString();
}
首次使用时,显示从1,2,3,4开始......但是当你再次点击时,它从2,4,6开始....再次点击,显示屏3,6 ...... 有没有办法让它在单击1,2,3,4按钮时运行显示器? 谢谢!
答案 0 :(得分:0)
使用Stop()
方法在每次点击之前停止计时器,然后再次运行。
private void btnrun_Click(object sender, RoutedEventArgs e)
{
t = 0;
timer2.Stop();
Start_timer();
}
每个计时器在同一Tick
回调中注册:
timer2.Tick += timer_Tick2;
所以这就是问题的原因。
答案 1 :(得分:0)
尝试这样的事情:
private void btnrun_Click(object sender, RoutedEventArgs e)
{
t = 0;
Start_timer();
}
public void Start_timer()
{
if (timer2 != null)
{
timer2 -= timer_Tick2; // unassigns the event handler
timer2.Stop(); // stops the timer
}
timer2 = new DispatcherTimer();
timer2.Tick += timer_Tick2;
timer2.Interval = new TimeSpan(0, 0, 0, 0, 1000);
timer2.Start();
}
void timer_Tick2(object sender, object e)
{
t++;
txttime.Text = t.ToString();
}
编辑:如果您只想启动计时器一次,可以将其缩小为:
private void btnrun_Click(object sender, RoutedEventArgs e)
{
t = 0;
if (timer2 == null)
Start_timer();
}
public void Start_timer()
{
timer2 = new DispatcherTimer();
timer2.Tick += timer_Tick2;
timer2.Interval = new TimeSpan(0, 0, 0, 0, 1000);
timer2.Start();
}
void timer_Tick2(object sender, object e)
{
t++;
txttime.Text = t.ToString();
}