Creating custom EventArgs containing additional data
suggest changeCustom events usually need custom event arguments that describe the event. MouseEventArgs, used by events such as MouseDown and MouseUp, carries the Location and the Button that raised the event.
When creating new events, to create a custom event arg:
- Create a class deriving from
EventArgsand define properties for necessary data. - As a convention, the class name should end with
EventArgs.
Example
In the example below, assigning Price raises PriceChanging. The event arguments carry CurrentPrice and NewPrice.
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; }
}
Product
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);
}
}
You can enhance the example by allowing the consumer to change the new value and then the value will be used for property. To do so it’s enough to apply these changes in classes.
Change the definition of NewPrice to be settable:
public int NewPrice { get; set; }
Change the definition of Price to use e.NewPrice as value of property, after calling OnPriceChanging :
int price;
public int Price
{
get { return price; }
set
{
var e = new PriceChangingEventArgs(price, value);
OnPriceChanging(e);
price = e.NewPrice;
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents