2010-06-03 204 views
1

我有一個情況,我想要一個給定的事件執行一次,只有一次。我試圖這樣做,但我有問題(否則我不會問)。請注意,以下代碼位於決定需要觸發事件的函數內部。使c#/ wpf事件只觸發一次?

EventHandler h = delegate(Object sender, EventArgs e) { 
    FiringControl.TheEvent -= h; // <-- Error, use of unassigned local variable "h" 
    // Do stuff 
} 
FiringControl.TheEvent += h; 

一般來說,這應該的,因爲範圍保存代表,直到後他們就完成了運行方式工作,但由於h是正在興建的過程中,當我嘗試使用它,它仍然被認爲是顯然是「未初始化」。

+0

http://stackoverflow.com/questions/1554845/am-i-using-the-right-approach-to-monitor-the-tasks-i-want-to-perform-when-a-handl/1554978 #1554978 – Juliet 2010-06-03 18:39:56

回答

3

您可以先設置h = null,然後將其設置爲等於其他值?喜歡這個?

EventHandler h = null; 

h = delegate(Object sender, EventArgs e) { 
    FiringControl.TheEvent -= h; // <-- Error, use of unassigned local variable "h" 
    // Do stuff 
} 

FiringControl.TheEvent += h; 

但是你確定這是正確的做法嗎?你想要做什麼整體?

+0

是的,這是完美的作品。剛剛發現並回來刪除問題,但我想我現在不會。 ;) – Donnie 2010-06-03 17:32:07

+0

至於我在做什麼,我暫時掛鉤'TheEvent'可能會取消另一個操作。 「問題」是可能有多個這樣的情況發生,所以我濫用本地作用域綁定與代表,以避免必須維護這些列表。 – Donnie 2010-06-03 17:33:59