Custom Event on Custom Control

六月ゝ 毕业季﹏ 提交于 2019-12-13 02:27:31

问题


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" />

回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/3669160/custom-event-on-custom-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!