3つのボタン(Button1、Button2、StartButton)とタイマーがあるwin8アプリをビルドします。 Button1とButton2は無効です。 StartButtonをクリックすると、Button1が有効になり、20秒以内のクリック数がカウントされ、テキストブロック1に表示されます。タイマーが終了するとButton1が無効になり、Button2が有効になり、クリック数がカウントされてtextblock2に表示されます。私の問題は、Button1ではなくButton2でタイマーが正しく動くことです。 button2を有効にすると、タイマーが速くなります。誰か助けてくれますか? 私のコードは以下の通りです: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 =ヌルを!)置くことによって、あなたの目のオプションに従うことを試みました。 timer.Tick - = timer_Tick; this.StopTimer();}正しいですか? – Shan
最初のメソッドを使用した場合、InitTimer()をどこで呼び出すべきですか? – Shan
あなたのMainPageのPageLoadedイベントでそれを呼び出すことをお勧めします。 –