There may be other solutions, but here's one that worked for me. I worked it out in VB.NET; you may want to modify if you work in C#. This is a very simple demo, but it works to show off the simple solution.
First, I'm assuming you have a class something like this:
Public Class MenuClass Private mName As String Private mLocation As String
Public Sub New(ByVal Name As String, ByVal Location As String) mName = Name mLocation = Location End Sub
Public ReadOnly Property Name() As String Get Return mName End Get End Property
Public ReadOnly Property Location() As String Get Return mLocation End Get End Property End Class
To give each new menu item a place to store a reference to one of these puppies, I created a new class that inherits from MenuItem that exposes a public instance of the MenuClass type:
Class MyMenuItem Inherits MenuItem
Public Item As MenuClass
Public Sub New(ByVal mc As MenuClass) MyBase.New(mc.Name) Item = mc End Sub End Class
In your form, outside any procedure, you'll need a reference to a WithEvents variable to trap menu item events:
Private WithEvents mi As MyMenuItem
You'll also need a procedure that will eventually handle the Click event of the menu items you add. This one takes the menu item it receives, casts it as a MyMenuItem object, retrieves the Item property (which is one of your MenuClass instances), and calls a procedure passing the Location property, as you requested:
Private Sub HandleMyMenuItems( _ ByVal sender As System.Object, ByVal e As System.EventArgs) Dim mi As MyMenuItem mi = DirectCast(sender, MyMenuItem) HandleMenuItem(mi.Item.Location) End Sub
Finally, you need a procedure that adds menu items, like this one. I tested this, adding items as I click a button on the form. In this case, all the items have the same Name and Location property--in your case, of course, they wouldn't:
Private Sub Button1_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click
Dim mc As New MenuClass("Name1", "Location1") mi = New MyMenuItem(mc) MainMenu1.MenuItems(0).MenuItems.Add(mi) AddHandler mi.Click, AddressOf HandleMyMenuItems End Sub
That's it. Each new menu item hooks up to call the same Click event handler, and each menu item has a MenuClass object (or whatever you call yours) associated with it, because each menu item is actually a MyMenuItem (or whatever you want to call it) instance.
I know this seems like a lot of code, but there's really not much here. Have fun! |