一种解决方案是创建一个伪造的后盾事件和查找字典用于存储您需要转发该事件的信息。例如:
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