2012-05-05 31 views
7

我開發在Windows 8的Visual Studio 11的應用程序,我想定義的事件處理程序,如下一DispatcherTimer實例:定義事件處理程序,在Windows DispatcherTimer的Tick事件8應用

public sealed partial class BlankPage : Page 
    { 

     int timecounter = 10; 
     DispatcherTimer timer = new DispatcherTimer(); 
     public BlankPage() 
     { 
      this.InitializeComponent(); 
      timer.Tick += new EventHandler(HandleTick); 
     } 

     private void HandleTick(object s,EventArgs e) 
     { 

      timecounter--; 
      if (timecounter ==0) 
      { 
       //disable all buttons here 
      } 
     } 
     ..... 
} 

但我得到以下錯誤:

Cannot implicitly convert type 'System.EventHandler' to 'System.EventHandler<object>' 

我是一個新手開發寡婦8應用程序。

你能幫我嗎?

回答

8

差不多已經有了:)你不需要實例化一個新的eventhandler對象,你只需要指向處理該事件的方法即可。因此,一個事件處理程序。

 int timecounter = 10; 
    DispatcherTimer timer = new DispatcherTimer(); 
    public BlankPage() 
    { 
     this.InitializeComponent(); 

     timer.Tick += timer_Tick; 
    } 

    protected void timer_Tick(object sender, object e) 
    { 
     timecounter--; 
     if (timecounter == 0) 
     { 
      //disable all buttons here 
     } 
    } 

試着讀了各位代表瞭解事件Understanding events and event handlers in C#

+0

的變化,但我們不Windows應用程序有這個問題?我們要不要 ? –

+0

代理和事件處理程序在整個平臺上都是相同的。這不是一個「問題」,它是如何工作:) – danielovich

+0

問題我的意思是'System.EventHandler ',我不是說這是一個錯誤 –

2

的WinRT使得使用泛型比標準.NET運行更多。 DispatcherTimer.Tick爲defined in WinRT is here

public event EventHandler<object> Tick 

雖然WPF DispatcherTimer.Tick is here 公共事件的EventHandler蜱

還要注意的是,你不必使用標準的命名方法來創建一個事件處理程序。你可以使用lambda來做到這一點:

int timecounter = 10; 
DispatcherTimer timer = new DispatcherTimer(); 
public BlankPage() 
{ 
    this.InitializeComponent(); 

    timer.Tick += (s,o)=> 
    { 
     timecounter--; 
     if (timecounter == 0) 
     { 
      //disable all buttons here 
     } 
    }; 
} 
3

你的代碼期望HandleTick有兩個對象參數。不是一個對象參數和一個EventArg參數。

private void HandleTick(object s, object e) 

private void HandleTick(object s,EventArgs e) 

這是發生了針對Windows 8

相關問題