我需要一个计时器,在 5 秒后将我重定向到另一个页面,问题是它每 5 秒将我重定向到此页面,所以我需要停止它。如果我在 tmr.Start() 之后停止它,它不会执行该事件。如何在 OnTimerTick
事件中执行此操作?
DispatcherTimer tmr = new DispatcherTimer();
tmr.Interval = TimeSpan.FromSeconds(5);
tmr.Tick += new EventHandler(OnTimerTick);
tmr.Start();
void OnTimerTick(object sender, EventArgs e)
{
NavigationService.Navigate(new Uri("/lvlSet1/s1lvl3.xaml", UriKind.Relative));
}
最佳答案
描述
两种可能的解决方案。
- 在类级别而不是在方法中创建
DispatcherTimer
实例。然后您可以从OnTimerTick
方法访问它们。 - 您可以在
OnTimerTick
方法中将发送方强制转换为DispatcherTimer
。
示例
<强>1。解决方案
public class YourClass
{
DispatcherTimer tmr = new DispatcherTimer();
public void YourMethodThatStartsTheTimer()
{
tmr.Interval = TimeSpan.FromSeconds(5);
tmr.Tick += new EventHandler(OnTimerTick);
tmr.Start();
}
void OnTimerTick(object sender, EventArgs e)
{
tmr.Stop();
NavigationService.Navigate(new Uri("/lvlSet1/s1lvl3.xaml", UriKind.Relative));
}
}
<强>2。解决方案
void OnTimerTick(object sender, EventArgs e)
{
((DispatcherTimer)sender).Stop();
NavigationService.Navigate(new Uri("/lvlSet1/s1lvl3.xaml", UriKind.Relative));
}
更多信息
关于windows-phone-7 - 如何通过外部事件停止 WP7 上的计时器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8607634/