我正在构建一个具有 3 个按钮(Button1、Button2 和 StartButton)和计时器的 win8 应用程序。Button1 和 Button2 被禁用。如果单击 StartButton,则启用 Button1,并计算 20 秒内的单击次数并显示在 textblock1 中。计时器结束后,Button1 被禁用,Button2 被启用,点击计数并显示在 textblock2 中。我的问题是 Button1 而不是 Button2 的计时器正确计时。启用 button2 后,计时器会变得更快。有人能帮我吗?我的代码如下:
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;
}
}