简体   繁体   English

将自定义控件中的事件动态添加到表单中

[英]Raising event from custom control added dynamically to the form

I have a custom control that can be added multiple times to a form. 我有一个自定义控件,可以多次添加到窗体。 There can be multiples occurrences of this custom control on the same form. 在同一表单上可以有多次出现此自定义控件。 These controls are added and removed by the user. 用户添加和删除这些控件。 The user can right click on some control inside the custom control to reveal a menu. 用户可以右键单击自定义控件内的某个控件来显示菜单。

When selecting an item from this menu, an event should be raised on the form. 从此菜单中选择项目时,应在表单上引发事件。 I made a custom event and realized that it could't be usable if the control was added dynamically, because the form doesn't know it. 我做了一个自定义事件,并意识到如果控件是动态添加的,它就无法使用,因为表单不知道它。 I can't add an event handler referring to a control that doesn't exist. 我无法添加一个引用不存在的控件的事件处理程序。 Is there some other way to raise an event on the form from custom control that doesn't require the form to know it? 是否有其他方法可以从自定义控件上提升表单上的事件,而不需要表单来知道它? By the way, my custom controls are added to a FlowLayoutPanel. 顺便说一句,我的自定义控件被添加到FlowLayoutPanel。 Thanks for the help! 谢谢您的帮助!

You just wire up the event handler in the code when you add the control eg 您只需在添加控件时在代码中连接事件处理程序,例如

MyButton.Click += ButonClickEventHandler;
Page.Controls.Add(MyButton)

Agree with Ben - otherwise, there are messy ways of doing it (depending on how your control is set up). 同意Ben - 否则,有一些混乱的方法(取决于你的控件如何设置)。 For example INotifyPropertChanged Inerface or through Windows API messaging (and listener) - but unless you have a very strange set up, then as Ben said, simply add a handler when you add the control. 例如INotifyPropertChanged Inerface或通过Windows API消息传递(和监听器) - 但除非你有一个非常奇怪的设置,然后如Ben所说,只需在添加控件时添加一个处理程序。 You can always use a generic callback method and use custom event args to identify which has triggered it. 您始终可以使用通用回调方法并使用自定义事件参数来标识触发它的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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