2012-08-02 77 views
1

在傳統的類庫,我可以這樣做:如何在WinRT類中裝飾事件?

public event EventHandler Changed 
{ 
    add { decorated.Changed += value; } 
    remove { decorated.Changed -= value; } 
} 

現在,如果我與WinRT的班級工作,編譯器會抱怨這樣的代碼。我設法修補'加',但堅持刪除:

public event EventHandler Changed 
{ 
    add { return decorated.Changed += value; } 
    remove { decorated.Changed -= value; } 
} 

我應該如何實施刪除部分?

+0

什麼是編譯器的抱怨? – 2012-08-02 09:19:30

+0

它說「不能隱式轉換類型'System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken'到'System.EventHandler '」 – Przemaas 2012-08-02 09:28:02

+1

是的,這改變了WinRT,EventRegistrationToken是必不可少的類型,它存儲了活動cookie。我只能找到一個C++/CX的例子:http://msdn.microsoft.com/en-us/library/windows/apps/hh755799%28v=vs.110%29.aspx – 2012-08-02 09:30:45

回答

1

委託和事件標記之間System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable<T>

存儲映射,支持託管代碼在Windows運行時事件的實現。

當您需要手動管理事件的添加和刪除時使用此類型。

此表的一個實例存儲代表已添加到事件的事件處理程序的委託。要提升事件,請調用由InvocationList屬性返回的代理,如果它不是null。每個事件都需要此表的一個實例。

例如,

private EventRegistrationTokenTable<EventHandler<Object>> _changed 
    = new EventRegistrationTokenTable<EventHandler<Object>>(); 

public event EventHandler<Object> Changed 
{ 
    add { return _changed.AddEventHandler(value); } 
    remove { _changed.RemoveEventHandler(value);  } 
} 
+0

是的 - 這是我如何實現我的自定義事件,但它不處理來自其他類的裝飾事件。如果我應該使用關聯的EventRegistrationTokenTable實例,我需要訪問它。它在裏面裝飾類。如果裝飾的類不公開它呢? – Przemaas 2012-08-03 08:31:15

0

一種解決方案是創建一個僞造的後盾事件和查找字典用於存儲您需要轉發該事件的信息。例如:

public event EventHandler<Object> Changed 
{ 
    add 
    { 
    // get fake token so that we can return something and/or unsubscribe 
    EventRegistrationToken token = _changed.AddEventHandler(value); 
    // subscribe and store the token-handler pair 
    _otherClass.Event += value; 
    _dictionary[token] = value; 
    return token; 
    } 
    remove 
    { 
    // recall value and remove from dictionary 
    _otherClass.Event -= _dictionary[value]; 
    _dictionary.Remove(value); 
    // remove it from the "fake" event 
    _changed.RemoveEventHandler(value); 
    } 
} 

private EventRegistrationTokenTable<EventHandler<Object>> _changed; 
private Dictionary<EventRegistrationToken, EventHandler<Object>> _dictionary; 

可替代地,它可以更容易地訂閱從WinRT的類中的CLR事件,並且簡單地將CLR事件到訂閱者的WinRT;或多或少顛倒你所問的流程:

public WinRtObject() 
{ 
    _otherClass.Event += (sender, o) => OnChanged(o); 
} 

public event EventHandler<Object> Changed; 

private void OnChanged(object e) 
{ 
    EventHandler<object> handler = Changed; 
    if (handler != null) 
    handler(this, e); 
}