Reputation: 2138
I have a user control that has a contextmenustrip that is displayed on every right click. When the user select an item on this menu, I have to pass this info to the parent control so it can react according to this.
So I need the parent to mandatory subscribe to this event. Is there a way to tell that?
If there is no way to do that, should I throw an exception or just check for null value (of the event handler) and do nothing?
Thanks.
Upvotes: 0
Views: 228
Reputation: 13897
You can create a specific constructor for your user control to prevent instantiation unless an event handler is given, like this.
public partial class MyUserControl : UserControl {
public MyUserControl (ToolStripItemClickedEventHandler handler) {
InitializeComponent ();
myContextMenuStrip.ItemClicked += handler;
}
}
Do note though: this won't work very well with Visual Studio's form designer, as the form designer generally expects parameter-less constructors. Instead, you need to manually create the control instance from code.
Upvotes: 2
Reputation: 55720
There is no way to enforce this at compile time - meaning that there is nothing in the .NET framework/C# language that can perform static checks at compilation to ensure that this logic is implemented in your code.
At run-time you can perform the necessary validation. For instance you might inspect the invocation list of the delegate to ensure that the parent is in that list.
Upvotes: 4