自定义控件上的自定义事件 [英] Custom Event on Custom Control

查看:163
本文介绍了自定义控件上的自定义事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义控件,我们将其称为 TheGrid。

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

在TheGrid的控件中,我们将其称为 GridMenu。

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

GridMenu在其自己的控件集合中有一个按钮控件。

GridMenu has a button control in its own control collection.

我想使使用此控件的开发人员能够将页面级方法与位于GridMenu ala中的该按钮的OnClick关联:

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


推荐答案

在GridMenu上(我认为这是另一个自定义控件),将事件ButtonClick声明为公开:

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

public event EventHandler ButtonClick;

如果愿意,可以通过定义委托和自定义事件参数来创建自定义事件处理程序类。在此控件的逻辑中的某个位置,您将需要引发事件(也许在GridMenu上包含的按钮的Clicked事件处理程序中;事件可以级联)。用C#编码,您需要在引发事件之前检查该事件是否不为null(意味着至少连接了一个处理程序)。

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.

现在该事件可见到TheGrid,其中包含您的GridMenu。现在,您需要创建一个传递,以允许TheGrid的用户附加处理程序,而不必了解GridMenu。您可以通过在TheGrid上指定一个类似于属性的事件,并从内部事件附加和分离处理程序来实现此目的:

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;}
}

现在,从包含TheGrid控件的控件的标记中,您可以通过将事件处理程序以所需的方式附加到OnGridMenuButtonClicked来指定事件处理程序。

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.

这篇关于自定义控件上的自定义事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆