The understanding of events in component programming is very important. The "events" in C # is a way that classes provide notifications to customers of this class when an object has something interesting. In my opinion, delegate-delegate can encapsulate method references in the delegate object. In order to understand the relationship between component-event-delegate, I will discuss the younger brother's understanding with practical examples.
First, create a Windows Control Project and add the following control template.
When an event is triggered, an EventArgs type parameter is passed to the event processing method. To pass custom information, we can create an event parameter class inherited from EventArgs, it is defined as follows:
Public class EventLoginArgs: System. EventArgs
{
Public string strUserID;
Public string strUserName;
Public string strUserPWD;
Public bool bVaild;
Public EventLoginArgs (string userID, string userName, string userPWD)
{
StrUserID = userID;
StrUserName = userName;
StrUserPWD = userPWD;
}
Two more delegates are declared, which encapsulate the information in the EventLoginArgs and EventArgs objects, as follows:
Public delegate void UserLoginEventHandler (object sender, EventLoginArgs e );
Public delegate void CancelEventHandler (object sender, EventArgs e );
To allow users to customize the processing method of an event, the component must provide an event interface. if you only inherit from a single existing Windows control, you can reload known methods to add your own processing, or declare custom event interfaces. if the component contains multiple controls, you should declare the event interface as needed. Here, I declare two custom event interfaces for the use of the two buttons, as shown below:
Public event UserLoginEventHandler SubmitLogin;
Public event CancelEventHandler Cancel;
Protected virtual void OnSubmitLogin (EventLoginArgs e)
{
If (this. SubmitLogin! = Null)
{
SubmitLogin (this, e );
}
}