2012-08-02 100 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); 
}