Click here to Skip to main content
15,561,011 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi all!

I am teaching myself WPF and slowly building my first application, so please be patient.

I have an array, named sProjectList, after which I add menuitems to a menu, this is working fine:

VB
Dim x As Integer
...
If IsArray(sProjectList) Then
    For i = sProjectList.GetLowerBound(0) To sProjectList.GetUpperBound(0)
        x = miProjectList.Items.Add(sProjectList(i, 0).ToString)
    Next i
End If


Now.. I need my menuitems to have a click event handler... how do I specify that? I have been searching but I am unable to find out... I tried getting a reference to the new menu item:

VB
Dim x As Integer
Dim mi As MenuItem
...
If IsArray(sProjectList) Then
            For i = sProjectList.GetLowerBound(0) To sProjectList.GetUpperBound(0)
                x = miProjectList.Items.Add(sProjectList(i, 0).ToString)
                mi = DirectCast(miProjectList.Items(x), MenuItem)
                '''what to do now???
            Next i
        End If



I am sure this is very easy, but I am just stuck on this one. Thank you in advance for your help!
Posted
Updated 25-Feb-11 4:16am
v2
Comments
Toli Cuturicu 25-Feb-11 9:16am    
Not c#. Removed misleading tag.
iris.frigole 25-Feb-11 11:03am    
you are right, i tagged c# because although i am using vb .net i was happy to receive c# code as an answer, as i was more interested in the logic than the language. thank you.

You Need to attach the event to the Menuitem
Menuitem+=new (Corresponding event Handler)(methodName)
 
Share this answer
 
Comments
iris.frigole 25-Feb-11 7:04am    
Accepting your answer, as (as far as i can tell) this is C# for

AddHandler mi.Click, AddressOf the_handler_sub

Thank you!
Espen Harlinn 25-Feb-11 7:32am    
Nice and simple, my 5
This is the VB.NET code that does the trick (the one posted with the question would give a runtime error when casting to menu item):

VB
Dim sProjectList(,) As Object 'array with project names and ids
Dim mi As MenuItem
...
If IsArray(sProjectList) Then
    For i = sProjectList.GetLowerBound(0) To sProjectList.GetUpperBound(0)
        mi = New MenuItem()
        mi.Header = sProjectList(i, 0).ToString
        AddHandler mi.Click, AddressOf subShowOneProject
        miProjectList.Items.Add(mi)
    Next i
End If


miProjectList is a menuitem I defined in the xaml file.
subShowOneProject is the procedure that handles the click event.

HTH,

Iris
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900