Để có thể ném một sự kiện ta làm các bước sau:
Bước 1: Khai báo phương thức uỷ quyền
// Events are handled with delegates, so we must establish a MyEventHandler as a delegate
public delegate void MyEventHandler(object sender, EventArgs e);
Bước 2: Khai báo Event
// Now, create a public event "MyEvent" whose type is our MyEventHandler delegate.
public event MyEventHandler MyEvent;
Bước 3: Ném sự kiện
public void MyMethod() {
EventArgs MyArgs = new EventArgs();
// Now, raise the event by invoking the delegate. Pass in the object that initated the event (this) as well as EventArgs.
// The call must match the signature of MyEventHandler.
MyEvent(this, MyArgs);
}
Ví dụ:
public class MyTextBox : System.Windows.Controls.TextBox
{
// Events are handled with delegates, so we must establish a MyEventHandler as a delegate
public delegate void MyEventHandler(object sender, EventArgs e);
// Now, create a public event "MyEvent" whose type is our MyEventHandler delegate.
public event MyEventHandler MyEvent;
public void MyMethod()
{
EventArgs MyArgs = new EventArgs();
// Now, raise the event by invoking the delegate. Pass in the object that initated the event (this) as well as EventArgs.
// The call must match the signature of MyEventHandler.
MyEvent(this, MyArgs);
}
}
Không có nhận xét nào:
Đăng nhận xét