一种解决方案是创建一个虚假的支持事件和查找字典,用于存储转发事件所需的信息。例如:
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);
}