Reputation: 627
I need a timer that redirects me to another page after 5 seconds, the problem is that it redirects me to this page every 5 seconds, so I need to stop it. If I stop It after tmr.Start()
It doesn't execute the event. How can I do this in the event 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));
}
Upvotes: 2
Views: 696
Reputation: 60438
Two possible solutions.
DispatcherTimer
instance on class level, not in your method. Then you can acces them from your OnTimerTick
Method. DispatcherTimer
in your OnTimerTick
method. 1. Solution
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. Solution
void OnTimerTick(object sender, EventArgs e)
{
((DispatcherTimer)sender).Stop();
NavigationService.Navigate(new Uri("/lvlSet1/s1lvl3.xaml", UriKind.Relative));
}
Upvotes: 4
Reputation:
Trying structuring your code like this. Is is going to keep your timer object in scope so you can stop it after the first tick happens.
class SimpleExample
{
DispatcherTimer timer;
public SimpleExample()
{
timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(5);
timer.Tick += new EventHandler(OnTimerTick);
}
public void SomeMethod()
{
timer.Start();
}
void OnTimerTick(object sender, EventArgs e)
{
timer.Stop();
NavigationService.Navigate(new Uri("/lvlSet1/s1lvl3.xaml", UriKind.Relative));
}
}
Upvotes: 1