我是C#的业余爱好者,我正在做一个项目。
我使用了3个计时器,其中一个是20秒计时器。 我希望在20秒过后,其他2个计时器必须停止
我无法从圆形计时器访问/调用其他2个计时器。 这是代码:
public void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
DispatcherTimer tgtTimer = new DispatcherTimer();
tgtTimer.Tick += new EventHandler(tgtTimer_tick);
tgtTimer.Interval = new TimeSpan(0, 0, 3);
tgtTimer.Start();
DispatcherTimer txbTimer2 = new DispatcherTimer();
txbTimer2.Tick += new EventHandler(txbTimer2_tick);
txbTimer2.Interval = new TimeSpan(0, 0, 0, 4, 000);
txbTimer2.Start();
DispatcherTimer rt = new DispatcherTimer();
rt.Tick += new EventHandler(rt_tick);
rt.Interval = new TimeSpan(0, 0, 1);
rt.Start();
}
private void tgtTimer_tick(object sender, EventArgs e)
{ //some code }
private void txbTimer2_tick(object sender, EventArgs e)
{ //some code }
int i = 20 //for the 20 sec round timer
private void rt_tick(object sender, EventArgs e) //round timer
{
if(i!=0)
{
i--;
txbTime.Text = "";
txbTime.Text = Convert.ToString(i) + "s";
}
else
{
this.Opacity = 0.3;
//tgtTimer and txbTimer2 can't be accessed from here
}
}
我应该如何停止2个计时器?
答案 0 :(得分:2)
你应该尝试在mouseleftbutton down事件之外添加定时器,如下所示:
DispatcherTimer tgtTimer = new DispatcherTimer();
DispatcherTimer txbTimer2 = new DispatcherTimer();
DispatcherTimer rt = new DispatcherTimer();
public void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
tgtTimer.Tick += new EventHandler(tgtTimer_tick);
tgtTimer.Interval = new TimeSpan(0, 0, 3);
tgtTimer.Start();
txbTimer2.Tick += new EventHandler(txbTimer2_tick);
txbTimer2.Interval = new TimeSpan(0, 0, 0, 4, 000);
txbTimer2.Start();
rt.Tick += new EventHandler(rt_tick);
rt.Interval = new TimeSpan(0, 0, 1);
rt.Start();
}
答案 1 :(得分:2)
将定时器的引用移出按钮单击:
DispatcherTimer tgtTimer = new DispatcherTimer();
DispatcherTimer tgtTimer2 = new DispatcherTimer();
public void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
DispatcherTimer tgtTimer = new DispatcherTimer(); //here
tgtTimer.Tick += new EventHandler(tgtTimer_tick);
tgtTimer.Interval = new TimeSpan(0, 0, 3);
tgtTimer.Start();
DispatcherTimer txbTimer2 = new DispatcherTimer(); //and here
txbTimer2.Tick += new EventHandler(txbTimer2_tick);
txbTimer2.Interval = new TimeSpan(0, 0, 0, 4, 000);
txbTimer2.Start();
//or inline the method to stay within scope
DispatcherTimer rt = new DispatcherTimer();
rt.Tick += (ob, ev) =>
{
//still in scope
txbTimer2.Start();
};
rt.Interval = new TimeSpan(0, 0, 1);
rt.Start();
}