0

So I'm working on an application that will need a timer on every page counting by the second. I figured it would be best to have the actual function on a class and have it called by the pages that need it. What I do know is how to get the timer working in a page... What baffles me is how to get it working in a class.

Needless to say, I'm failing.

Here's what I've done in the class:

    namespace Masca
    {
    public class timer
    {

    public void StartTimer()
    {
        System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
        dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
        dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
        dispatcherTimer.Start();
    }

    private void dispatcherTimer_Tick(object sender, EventArgs e)
    {
        DateTime datetime = DateTime.Now;
    }

And what I've done in a page I need the timer in

namespace Masca
{

public partial class signup : Elysium.Controls.Window
{
    public timer timer;

    public signup(string Str_Value)
    {

        InitializeComponent();
        tag.Text = Str_Value;
    }

    public void dispatcherTimer_Tick(object sender, EventArgs e)
    {
        DateTime datetime = DateTime.Now;
        this.doc.Text = datetime.ToString();
    }

I can't get the 'dispatcherTimer_Tick' event to know it's supposed to get it's instructions on how to work from the class 'timer'.

Any ideas on how to do this?

2 Answers 2

1

You probably want to add an event to your timer class:

public class timer
{

public event EventHandler TimerTick;

private void dispatcherTimer_Tick(object sender, EventArgs e)
{
    if (TimerTick != null)
        TimerTick(this, null);
}

So that in your Window you can just listen to this event.

Sign up to request clarification or add additional context in comments.

Comments

0

You will need to expose either your own event or delegate from your timer class. The external classes subscribe to this event/delegate and you raise/call it from the dispatcherTimer_Tick method in your timer class.

I would do something like this in your timer class:

public delegate void TimeUp(); // define delegate

public TimeUp OnTimeUp { get; set; } // expose delegate

...

private void dispatcherTimer_Tick(object sender, EventArgs e)
{
    DateTime datetime = DateTime.Now;
    if (OnTimeUp != null) OnTimeUp(); // call delegate
}

And from outside the class:

public timer timer;  

...

timer.OnTimeUp += timerOnTimeUp;

private void timerOnTimeUp()
{
    // time is up
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.