控件中的Events个人理解。
首先,了解一下与事件和委托有关的几个类和属性:
Delegate, MulticastDelegate, EventHandler, EventHandlerList, EventHandlerList.ListEntry, Control, Component
Control的Events属性是由System.ComponentModel.Component 继承而来,它是EventHandlerList的实例.
public void AddHandler(object key, Delegate value);
public void RemoveHandler(object key, Delegate value);
private ListEntry Find(object key);
示例:我们要为当前控件添加一个点击事件(Click).
第一步:创建一个静态只读的属性
public static readonly object ClickEvent=new object(); //它是以后事件查找委托的键(key),
第二步:注册事件
public event EventHandler Click
{
add
{
base.Events.AddHandler(ClickEvent,value);
}
remove
{
base.Events.RemoveHandler(ClickEvent,value);
}
}
----
以下是Events的定义:
private EventHandlerList events;
protected EventHandlerList Events
{
get
{
if (this.events == null)
{
this.events = new EventHandlerList();
}
return this.events;
}
}
Delegate, MulticastDelegate, EventHandler, EventHandlerList, EventHandlerList.ListEntry, Control, Component
Control的Events属性是由System.ComponentModel.Component 继承而来,它是EventHandlerList的实例.
EventHandlerList类有三个重要的方法:
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
示例:我们要为当前控件添加一个点击事件(Click).
第一步:创建一个静态只读的属性
public static readonly object ClickEvent=new object(); //它是以后事件查找委托的键(key),
第二步:注册事件
public event EventHandler Click
{
add
{
base.Events.AddHandler(ClickEvent,value);
}
remove
{
base.Events.RemoveHandler(ClickEvent,value);
}
}
----
以下是Events的定义:
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
![](/Images/OutliningIndicators/None.gif)
<h3>
心静似高山流水不动,心清若巫峰雾气不沾。
</h3>
心静似高山流水不动,心清若巫峰雾气不沾。
</h3>