views:

153

answers:

3

Hello, I have a singleton timer in my WP7 application however I have no idea how to get it to update a textblock everytime the timer ticks... Is there a way to get the event handler of the timer ticking and then update the textbox with the correct time?

Here is what I tried to use but wouldn't work:

public _1()
    {
        InitializeComponent();
        Singleton.TimerSingleton.Timer.Tick += new EventHandler(SingleTimer_Tick);
    }

    void SingleTimer_Tick(object sender)
    {
        textBlock1.Text = Singleton.TimerSingleton.TimeElapsed.TotalSeconds.ToString();
    }

Here is my Timer.cs SingleTon:

http://tech-fyi.net/code/timer.cs.txt

+3  A: 

The method SingleTimer_Tick gets executed on a non GUI thread. Call

textBlock1.Invoke(() => textBlock1.Text = Singleton.TimerSingleton.TimeElapsed.TotalSeconds.ToString());

hawk
It gives me the error that there is no diff for Invoke :/?
Ryanb58
The question you posted was incomplete. Look at my other answer.
hawk
A: 

I'm not sure which type your timer is. Some are used to raise events on a thread pool thread, others on the GUI thread. If you could tell us the type of your timer (System.Timers.Timer, System.Threading.Timer etc.) then I can tell you what it's used for. However, if I remember correctly, Tick is used for the GUI timer whereas Elapsed is used for other timers - I might be wrong.

At the risk of patronizing you, I'm going to ask if you've started your timer or not :) Usually a call to Start() or setting Enabled to true will kick off a timer object. If you expect the timer to already be running you should be able to check a property such as Enabled to assert that it's running before you hook up the event.

Apart from that I'd do some printf style debugging to check that the event's actually being raised.

Alex Humphrey
Updated post above:)
Ryanb58
And yes I do Start the timer:)
Ryanb58
+2  A: 
void SingleTimer_Tick(object sender)

The method above should be something like

void SingleTimer_Tick(object sender, EventArgs e)

And when you ask a question please get your terminology right and give more details. It'll help you get the right answer faster. For example when you say "the application won't let me call ..." what you actually mean is the compiler gives you an error.

hawk
+1 - and DispatcherTimer's Tick event is raised on the 'GUI' thread, so there *shouldn't* be any problems there.
Alex Humphrey
@Alex Humphrey- That's right, I forgot to include that in the description.
hawk