【发布时间】:2014-08-08 01:59:26
【问题描述】:
我不知道如何解释清楚,但我会尽力而为。 我在我的 windows phone 8 项目中使用了 DispatcherTimer 类。我有一些复选框,当检查一个复选框时,将按钮从公交时间表开始按下倒计时。这里一切正常,但是当我取消选中复选框并选中另一个复选框时,相同的巴士时间开始,现在它下降(倒计时)2 秒。如果我取消选中复选框并再次选中另一个复选框,同时开始倒计时并且倒计时 3 秒...我不明白怎么做,因为在 click_event 上总是有一个新的类实例。 解决问题的唯一方法是重新加载我的 wp8 页面并再次检查某些内容,然后按下按钮开始倒计时。 注意:我正在从一个 .txt 文件中读取我的时间,该文件存储在我的项目中的一个文件夹中(使用 streamreader)。 有什么建议吗?
这里有一些代码:
CheckBox[] listchekbox;
DispatcherTimer timer;
private void Button_Click(object sender, RoutedEventArgs e)//BUTTON CLICK
{
timer = new DispatcherTimer();
listchekbox = new CheckBox[4] { Check1, Check2, Check3, Check4 };
if (Onlyoneclick(listchekbox, 0)) { Gettingbustime(path_names[0]); }
else if (Onlyoneclick(listchekbox, 1)) { Gettingbustime(path_names[1]); }
timer.Interval = new TimeSpan(0,0,1);
timer.Tick += onclick;
timer.Start();
}
private void onclick(object sender, EventArgs e) // TIMER EVENT COUNT
{
Countdown(bus1); // the parameter is the textbox where the result is displayed
Countdown(bus2);
}
private bool Onlyoneclick(CheckBox[] itemselected,int id) // this is not so important
{
int itemcounter = 0;
int falsecounter = 0;
for (int i = 0; i < listchekbox.Length; i++)
{
if (itemselected[i].IsChecked == true && id == i)
{
itemcounter++;
}
else if (itemselected[i].IsChecked == true) { falsecounter++; }
}
if (itemcounter == 1 && falsecounter==0) { return true; }
else { return false; }
}
public void Countdown(TextBlock tx)
{
string minute = tx.Text.Substring(0, 2);
string sekunde = tx.Text.Substring(3, 2);
int minute1 = Convert.ToInt32(minute);
int sekunde1 = Convert.ToInt32(sekunde);
sekunde1 = sekunde1 - 1;
if (sekunde1 < 0)
{
minute1 = minute1 - 1;
sekunde1 = 59;
}
if (minute1 < 0)
{
timer.Stop();
MessageBox.Show("Autobus left!");
}
if (sekunde1 < 10) { tx.Text = minute1.ToString() + ":0" + sekunde1.ToString(); }
else { tx.Text = minute1.ToString() + ":" + sekunde1.ToString(); }
if (minute1 < 10) { tx.Text = "0" + minute1.ToString() + ":" + sekunde1.ToString(); }
if (minute1 < 10 && sekunde1 < 10) { tx.Text = "0" + minute1.ToString() + ":0" + sekunde1.ToString(); }
}
【问题讨论】:
-
你正在创建一个 new 计时器,你没有停止旧的计时器。它继续滴答作响。
-
我做了,但代码中没有显示。似乎计时器类应该只创建一次,在类的初始构造函数中只能解决问题,虽然我不知道为什么
标签: c# windows-phone-8 dispatchertimer