DarioDP
DarioDP

Reputation: 627

How can I stop a timer on WP7 from an external event?

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

Answers (2)

dknaack
dknaack

Reputation: 60438

Description

Two possible solutions.

  1. Create your DispatcherTimer instance on class level, not in your method. Then you can acces them from your OnTimerTick Method.
  2. You can cast the sender to DispatcherTimer in your OnTimerTick method.

Sample

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));
    } 

More Information

MSDN: DispatcherTimer Class

Upvotes: 4

user60456
user60456

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

Related Questions