2017-06-06 112 views
1

我試圖找出一種方法,使我的事件註冊和取消註冊同步從我的初始化和清理。 我想要的是能夠調用通用方法來註冊或取消註冊一個事件,並只傳遞一個布爾值來進行操作。註冊/取消註冊事件處理程序的一般方法

我不想使用Window,但這是一個簡單的示例。

class EventSample 
{ 
    private Window myWindow; 

    public EventSample(Window window) 
    { 
     myWindow = window; 
     InitEvent(true); 
    } 

    ~EventSample() 
    { 
     InitEvent(false); 
    } 

    private void InitEvent(bool register) 
    { 
     // I want a generic similar to that 
     RegisterEvent(register, myWindow.Activated, MyWindow_Activated); 
     RegisterEvent(register,myWindow.Closed , MyWindow_Closed); 
     RegisterEvent(register, myWindow.Closing ,MyWindow_Closing); 
    } 



    private void MyWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e) 
    { 

    } 

    private void MyWindow_Closed(object sender, EventArgs e) 
    { 
    } 

    private void MyWindow_Activated(object sender, EventArgs e) 
    { 

    } 
} 
+0

它是WPF嗎? 'RegisterEvent'方法是怎麼樣的? –

回答

0

我遇到了類似的清理方法問題。我通過在處理窗口或控件時保留一系列要執行的操作來解決此問題。

事情是這樣的:

this.RegisterEvent 
    (() => this.Event += handler 
    ,() => this.Event -= handler 
    ); 

RegisterEvent執行(在我的情況下延遲)的事件附件:

private List<Action> unregisterEvents = new List<Action>(); 

private void RegisterEvent(Action registerAction, Action unregisterAction) 
{ 
    registerAction.Invoke(); 

    unregisterEvents.Add(unregisterAction); 
} 

在處置,只是走在註銷事件:

foreach (Action a in unregisterEvents) 
{ 
    a.Invoke(); 
} 
相關問題