Defining an event for a custom window control

I am working on a custom control.the element, which is a MonthCalendar MonthCalendar control, like Visual Studio (C #), and I want to define an event for my control. How to define a new event for a custom element of this form?

+4
source share
2 answers

If your event should not contain any additional information (Foo is the name of your event):

public event EventHandler Foo; 

And lift it like this:

 protected virtual void OnFoo() { if (Foo != null) Foo(this, EventArgs.Empty); } 

If you need to pass some additional information to event handlers, then create your own argument class, inheriting from EvenArgs class

 public class FooEventArgs : EventArgs { public string Message { get; private set; } public FooEventArgs(string message) { Message = message; } } 

Declare an event this way:

 public event EventHandler<FooEventArgs> Foo; 

And lift it like this:

 protected virtual void OnFoo(string message) { if (Foo != null) Foo(this, new FooEventArgs(message)); } 

It is good practice to create protected methods for creating events by descendants of the class where the event is declared. It is also recommended that you use the event naming convention:

  • add the -ing suffix to the event name for events that were raised before something happened (often you can cancel such events) (for example, checking)
  • add -ed suffix to the event name for events that occurred after something happened (for example, clicked)

As Torsten said, it’s good practice to create virtual methods for raising events. This not only allows you to raise events from descendants, but also disable event creation, or add some behavior before / after the event.

+8
source
 public event EventHandler<EventArgs> YourEvent; 
0
source

Source: https://habr.com/ru/post/1411704/


All Articles