HOW TO:使用事件屬性處理多個事件
更新:2007 年 11 月
若要使用事件屬性 (Visual Basic 2005 中的自訂事件),您必須在引發事件的類別中定義事件屬性,然後在處理事件的類別中設定事件屬性的委派。若要在類別中實作多個事件屬性,該類別內部必須儲存及維護為每個事件所定義的委派。典型的方法是實作以事件索引鍵編製索引的委派集合。
如果要儲存每個事件的委派,您可以使用 EventHandlerList 類別,或只實作自己的集合。集合類別必須提供方法,根據事件索引鍵來設定、存取和擷取事件處理常式委派。例如,您可以使用 Hashtable 類別,或者從 DictionaryBase 類別衍生自訂類別。委派集合的實作詳細資料不需要公開至類別之外。
類別內的每個事件屬性,都會定義一個 add 存取子方法和一個 remove 存取子方法。事件屬性的 add 存取子會在委派集合中加入輸入委派執行個體。事件屬性的 remove 存取子會從委派集合中移除輸入委派執行個體。事件屬性存取子會使用事件屬性的預先定義索引鍵,從委派集合新增和移除執行個體。
若要使用事件屬性處理多重事件
在引發事件的類別內定義委派集合。
定義每個事件的索引鍵。
在引發事件的類別中定義事件屬性。
使用委派集合實作事件屬性的 add 和 remove 存取子方法。
使用公用事件屬性,在處理事件的類別中新增和移除事件處理常式。
範例
下列 C# 範例使用 EventHandlerList 儲存每個事件的委派,以實作 MouseDown 和 MouseUp 事件屬性。事件屬性建構的關鍵字是以粗體字表示。
![]() |
---|
在 Visual Basic 2005 中不支援事件屬性。 |
// The class SampleControl defines two event properties, MouseUp and MouseDown.
class SampleControl: Component {
// :
// Define other control methods and properties.
// :
// Define the delegate collection.
protected EventHandlerList listEventDelegates = new EventHandlerList();
// Define a unique key for each event.
static readonly object mouseDownEventKey = new object();
static readonly object mouseUpEventKey = new object();
// Define the MouseDown event property.
public event MouseEventHandler MouseDown {
// Add the input delegate to the collection.
add { listEventDelegates.AddHandler(mouseDownEventKey, value); }
// Remove the input delegate from the collection.
remove { listEventDelegates.RemoveHandler(mouseDownEventKey, value); }
}
// Define the MouseUp event property.
public event MouseEventHandler MouseUp {
// Add the input delegate to the collection.
add { listEventDelegates.AddHandler(mouseUpEventKey, value); }
// Remove the input delegate from the collection.
remove { listEventDelegates.RemoveHandler(mouseUpEventKey, value); }
}
}
請參閱
工作
概念
參考
System.ComponentModel.EventHandlerList