简体   繁体   中英

Custom Event on Custom Control

I've got a custom control we'll call "TheGrid".

In TheGrid's controls is another control we'll call "GridMenu".

GridMenu has a button control in its own control collection.

I'd like to enable the developer using this control to associate a page level method with the OnClick of that button deep down inside GridMenu ala:

<customcontrols:TheGrid id="tehGridz" runat="server" onGridMenuButtonClick="mypagemethod" />

On the GridMenu (which I assume is another custom control), expose the event ButtonClick by declaring it as public:

public event EventHandler ButtonClick;

If you like, you can create a custom event handler by defining a delegate, and a custom event argument class. Somewhere in the logic of this control, you will need to raise the event (perhaps in the Clicked event handlers of buttons contained on GridMenu; events can cascade). Coding in C#, you'll need to check that the event is not null (meaning at least one handler is attached) before raising the event.

Now this event is visible to TheGrid, which contains your GridMenu. Now you need to create a "pass-through" to allow users of TheGrid to attach handlers without having to know about GridMenu. You can do this by specifying an event on TheGrid that resembles a property, and attaches and detaches handlers from the inner event:

public event EventHandler GridMenuButtonClick
{
   add{ GridMenu.ButtonClick += value;}
   remove { GridMenu.ButtonClick -= value;}
}

From the markup of a control containing a TheGrid control, you can now specify the event handler by attaching it to OnGridMenuButtonClicked the way you wanted.

You can register an event handler for this event using delegates. See the following MSDN articles:

http://msdn.microsoft.com/en-us/library/system.eventhandler%28VS.71%29.aspx

http://msdn.microsoft.com/en-us/library/aa720047%28v=VS.71%29.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM