Creating cancelable event
suggest changeA cancelable event can be raised by a class when it is about to perform an action that can be canceled, such as the FormClosing event of a Form.
To create such an event:
- Create a new event arg deriving from
CancelEventArgsand add additional properties for event data. - Create an event using
EventHandler<T>and use the new cancel event arg class which you created.
Example
In the example below, assigning Price raises PriceChanging. Value is the price that would be stored. If the consumer sets Cancel, the previous Price is kept:
PriceChangingEventArgs
public class PriceChangingEventArgs : CancelEventArgs
{
int value;
public int Value
{
get { return value; }
}
public PriceChangingEventArgs(int value)
{
this.value = value;
}
}
Product
public class Product
{
int price;
public int Price
{
get { return price; }
set
{
var e = new PriceChangingEventArgs(value);
OnPriceChanging(e);
if (!e.Cancel)
price = value;
}
}
public event EventHandler<PriceChangingEventArgs> PriceChanging;
protected void OnPriceChanging(PriceChangingEventArgs e)
{
var handler = PriceChanging;
if (handler != null)
handler(this, e);
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents