【问题标题】:Dispatch timer won't work调度计时器不起作用
【发布时间】:2015-12-18 03:05:13
【问题描述】:

我试图弄清楚调度计时器是如何工作的,以便我可以将它实现到我的程序中,我按照网站上的确切说明并寻找堆栈溢出的答案。人们说他们的问题已解决,但我有非常相似的代码,它不会工作......

错误是:

“timer_Tick”没有重载匹配委托“EventHandler

我能做什么?

public MainPage()
{
    this.InitializeComponent();

    DispatcherTimer timer = new DispatcherTimer();
    timer.Interval = TimeSpan.FromSeconds(1);
    timer.Tick += timer_Tick;
    timer.Start();
}

void timer_Tick(EventArgs e)
{
    TimeRefresh();
}

【问题讨论】:

    标签: c# uwp dispatchertimer


    【解决方案1】:

    您需要修复事件处理程序签名。它缺少发件人,第二个参数的类型只是object(见documentation。)

    void timer_Tick(object sender, object e)
    {
        TimeRefresh();
    }
    

    您还需要在类的顶部添加using Windows.UI.Xaml;,或者使用完整的命名空间实例化计时器:

    Windows.UI.Xaml.DispatcherTimer timer = new Windows.UI.Xaml.DispatcherTimer();
    

    如果有人偶然发现并使用 WPF,它有它自己的DispatchTimer。确保您引用的是“WindowsBase”(默认情况下应该存在)。签名略有不同。

    void timer_Tick(object sender, EventArgs e)
    {
        TimeRefresh();
    }
    

    它所在的命名空间也不同。要么将using System.Windows.Threading; 添加到顶部,要么使用完整的命名空间进行限定:

    System.Windows.Threading.DispatcherTimer timer
        = new System.Windows.Threading.DispatcherTimer();
    

    如果您使用的是 WinForms,您希望使用不同的计时器。 Read this WinForms Timer 和 WPF DispatchTimer 的区别。

    【讨论】:

    • 我使用 DispatchTimer,但是当我使用 System.Windows.Threading.DispatcherTimer 时,它会显示 The type or namespace name 'Threading' does not exist in the namespace 'System.Windows' (are you missing an assembly reference?)
    • 必须缺少System.Windows.Threading 程序集参考
    • @Victor ,我该如何添加?
    • 也许我缺少“WindowsBase.dll”我之前没有添加引用,如何尝试查看它是否丢失并添加它?
    • 不,我看到的只是 system.windows
    【解决方案2】:

    你必须指定事件的来源。

    void timer_Tick(object sender,EventArgs e)
    {
        TimeRefresh();
    }
    

    并且事件注册应该是这样的:

    timer.Tick += new EventHandler(timer_Tick);
    

    Here您可以阅读有关事件和事件处理程序的更多信息

    【讨论】:

      猜你喜欢
      • 2013-09-01
      • 2023-04-02
      • 1970-01-01
      • 2019-08-22
      • 2016-08-10
      • 2018-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多