2015-12-18 96 views
0

我想弄清楚一個調度計時器是如何工作的,所以我可以實現它到我的程序中,我遵循網站上的確切說明並尋找堆棧溢出的答案。人們說,他們的問題是固定的,但我有非常相似的代碼,它不會工作...調度計時器不會工作

的錯誤是:

無過載爲「timer_Tick」匹配下放「事件處理<對象>」

我該怎麼辦?

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

回答

5

您需要修復事件處理程序簽名。它缺少發件人,第二個參數的類型只是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定時器和WPF DispatchTimer之間的區別。

+0

仍然無法工作。同樣的錯誤 – Albert

+0

我使用DispatchTimer,但是當我使用'System.Windows.Threading.DispatcherTimer'它說'名字空間'System.Windows'中不存在類型或命名空間名稱'線程'(你是否缺少程序集引用? )' – Albert

+0

你幾乎在那裏。只需將'using System.Windows.Threading;'添加到您的類的頂部。 –

3

您必須指定事件的來源。

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

且事件登記應該是這樣的:

timer.Tick += new EventHandler(timer_Tick); 

Here你可以閱讀更多有關事件和事件處理程序