一種解決方案是創建一個僞造的後盾事件和查找字典用於存儲您需要轉發該事件的信息。例如:
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);
}
什麼是編譯器的抱怨? – 2012-08-02 09:19:30
它說「不能隱式轉換類型'System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken'到'System.EventHandler'」 –
Przemaas
2012-08-02 09:28:02
是的,這改變了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