自定义事件通常需要包含有关事件信息的自定义事件参数。例如MouseEventArgs,鼠标事件(例如MouseDown或MouseUp事件)所使用的包含有关事件的信息Location或Buttons用于生成事件的信息。
创建新事件时,要创建自定义事件arg:
创建一个派生类EventArgs并定义必要数据的属性。
按照惯例,该类的名称应以结尾EventArgs。
例
在下面的示例中,我们PriceChangingEventArgs为Price类的属性创建一个事件。事件数据类包含CurrentPrice和NewPrice。当您为Price属性分配新值时,该事件引发,并让消费者知道该值正在变化,并让他们知道当前价格和新价格:
PriceChangingEventArgs
public class PriceChangingEventArgs : EventArgs
{
public PriceChangingEventArgs(int currentPrice, int newPrice)
{
this.CurrentPrice= currentPrice;
this.NewPrice= newPrice;
}
public int CurrentPrice { get; private set; }
public int NewPrice { get; private set; }
}产品
public class Product
{
public event EventHandler<PriceChangingEventArgs> PriceChanging;
int price;
public int Price
{
get { return price; }
set
{
var e = new PriceChangingEventArgs(price, value);
OnPriceChanging(e);
price = value;
}
}
protected void OnPriceChanging(PriceChangingEventArgs e)
{
var handler = PriceChanging;
if (handler != null)
handler(this, e);
}
}您可以通过允许使用者更改新值来增强示例,然后将该值用于属性。为此,将这些更改应用于类就足够了。
将的定义更改NewPrice为可设置的:
public int NewPrice { get; set; }调用后,更改Price要e.NewPrice用作属性值的定义OnPriceChanging :
int price;
public int Price
{
get { return price; }
set
{
var e = new PriceChangingEventArgs(price, value);
OnPriceChanging(e);
price = e.NewPrice;
}
}