简体   繁体   中英

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. 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). 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. You can always use a generic callback method and use custom event args to identify which has triggered it.

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