1
我正在构建一个win8应用程序,它有3个按钮(Button1,Button2和StartButton)和计时器。 Button1和Button2被禁用。如果单击StartButton,Button1被启用,并且20秒内的点击次数被计入并显示在文本块1中。定时器结束后,Button1被禁用,Button2被启用,点击被计数并显示在textblock2中。我的问题是,计时器适用于Button1而不适用于Button2。当启用按钮2时,计时器变快。有人能帮我吗? 我的代码如下:Win8应用程序中的计时器计数
private int count1=0;
private int count2=0;
private int clickCounter = 0;
private int timeLeft;
private DispatcherTimer timer;
private void StartTimer()
{
if (this.timer != null)
{
this.StopTimer();
}
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = new TimeSpan(0,0,0,1);
timer.Tick += timer_Tick;
timer.Start();
}
private void StopTimer()
{
if (this.timer != null)
{
this.timer.Stop();
this.timer = null;
}
}
public void timer_Tick(object sender, object args)
{
if (timeLeft > 0)
{
timeLeft = timeLeft - 1;
timerTextBlock.Text = Convert.ToString(timeLeft);
this.StartButton.IsEnabled = false;
}
else
{
StopTimer();
if (clickCounter==2)
{
ShowResult();
this.Button2.IsEnabled = false;
this.StartButton.IsEnabled = false;
}
else
{
myMsg.Text = "Time's up!";
this.Button1.IsEnabled = false;
this.StartButton.IsEnabled = true;
}
}
}
private void Button1_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
// TODO: Add event handler implementation here.
count1++;
this.textblock1.Text=count1.ToString();
}
private void Button2_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
count2++;
this.textblock2.Text=count2.ToString();
}
public void ResetTimer()
{
timeLeft = 20;
}
private void StartButton_Click(object sender, RoutedEventArgs e)
{
clickCounter++;
if (textblock1.Text == "0")
{
ResetTimer();
StartTimer();
this.Button1.IsEnabled = true;
}
else
{
ResetTimer();
StartTimer();
this.Button2.IsEnabled = true;
}
}
我删除startTimer所()内定时器变量,并试图通过把如果(this.timer!= NULL)跟随你的第二个选项{这一点。 timer.Tick - = timer_Tick; this.StopTimer();}它是正确的吗? – Shan
如果我使用你的第一个方法,那么我应该在哪里调用InitTimer()? – Shan
最好是在MainPage的PageLoaded事件中调用它。 –