繁体   English   中英

如何在类中实现调度程序计时器并调用它

[英]How to implement dispatcher timer in class and call it

因此,我正在开发一个应用程序,该应用程序需要在每个页面上按秒计数的计时器。 我认为最好在类上具有实际功能,并由需要它的页面调用它。 我所知道的是如何使计时器在页面中工作...让我感到困惑的是如何使其在班级中工作。

不用说,我失败了。

这是我在课堂上所做的事情:

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

我在页面中完成的操作需要使用计时器

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

我无法获得'dispatcherTimer_Tick'事件,以了解它应该从类'timer'中获取有关如何工作的说明。

有关如何执行此操作的任何想法?

您可能想将事件添加到计时器类中:

public class timer
{

public event EventHandler TimerTick;

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

这样一来,您就可以在Window中收听此事件。

您将需要公开自己的事件或timer类的委托。 外部类订阅此事件/委托,然后从timer类中的dispatcherTimer_Tick方法引发/调用它。

我会在您的timer类中执行以下操作:

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
}

从课堂之外:

public timer timer;  

...

timer.OnTimeUp += timerOnTimeUp;

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM