建立可取消的事件
可取消的事件可以由一個類被升高,當它是即將執行可以取消的動作,如 FormClosing 一個的事件 Form 。
要建立此類事件:
- 建立一個源自
CancelEventArgs的新事件 arg,併為事件資料新增其他屬性。 - 使用
EventHandler<T>建立一個事件,並使用你建立的新取消事件 arg 類。
例
在下面的示例中,我們為類的 Price 屬性建立了 PriceChangingEventArgs 事件。事件資料類包含一個 Value,讓消費者知道新的。當你為 Price 屬性分配新值並讓消費者知道值正在改變並讓他們取消該事件時,該事件會引發。如果消費者取消該事件,將使用 Price 的先前值:
PriceChangingEventArgs
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);
}
}