可取消的事件可以由一个类被升高,当它是即将执行可以取消,如一个动作FormClosing 的事件Form。
要创建此类事件:
创建一个新的事件 arg 派生自CancelEventArgs事件数据并为事件数据添加其他属性。
使用EventHandler<T>您创建的新取消事件 arg 类创建事件。
例子
在下面的示例中,我们PriceChangingEventArgs为Price类的属性创建了一个事件。事件数据类包含一个Value让消费者知道新的 . 当您为Priceproperty分配一个新值并让消费者知道该值正在更改并让他们取消该事件时,该事件就会引发。如果消费者取消该事件,则将使用之前的值Price:
价格变动事件参数
public class PriceChangingEventArgs : CancelEventArgs
{
int value;
public int Value
{
get { return value; }
}
public PriceChangingEventArgs(int value)
{
this.value= value;
}
}产品
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> PropertyChanging;
protected void OnPriceChanging(PriceChangingEventArgs e)
{
var handler = PropertyChanging;
if (handler != null)
PropertyChanging(this, e);
}
}