WPF How to acces and edit the MenuItems of a Menu?
-
Wednesday, February 29, 2012 2:54 PM
Hello!
I am currently switching my Windows Forms project to WPF and am encountering several issues, one of which is the fact that I can't seem to manage accessing the MenuItems of a menu I have programmatically. I mean, all that I can acces through [menuName].Items[index] is the header, but I want to add events and even trigger a renderTransformation. Casting that code to MenuItem simply returns an error stating that "System.String" cannot be converted to MenuItem...
Is there at least a way to do something like this?
Thank you!
EDIT:
This is tha XAML part:
<Menu Height="40" HorizontalAlignment="Left" Margin="50,80,0,0" Name="days_menu" VerticalAlignment="Top" Width="390" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" FontWeight="Bold" Background="{x:Null}"> <Menu.RenderTransform> <RotateTransform CenterX="0" CenterY="0" Angle="90"> </RotateTransform> </Menu.RenderTransform> </Menu>Through the days_menu.Items.Add(STRING) method I add the menu Items. That is all that I have by now.
- Edited by Antonius74 Wednesday, February 29, 2012 4:15 PM Request
All Replies
-
Wednesday, February 29, 2012 4:09 PM
Hi,
Is it possible to paste your code here?
/Srinivas
-
Wednesday, February 29, 2012 5:29 PMModerator
Your main problem is you are trying to convert your understanding of MenuItems from WinForm to WPF.
They are two different things.
The "Item" in the Menu.Items collection is a class representing the object behind the MenuItem (in your case it is a string) not the MenuItem itself.
var myValue = days_menu.Items[0] as string;
I would advise you take a step back and read up a bit more on WPF menus :
http://stackoverflow.com/questions/291522/wpf-how-can-you-add-a-new-menuitem-to-a-menu-at-runtime
http://www.c-sharpcorner.com/UploadFile/munnamax/WPFMenuItem09032007085818AM/WPFMenuItem.aspx
http://msdn.microsoft.com/en-us/library/ms747430.aspx
Regards,
Pete#PEJL
- Marked As Answer by Antonius74 Wednesday, February 29, 2012 6:20 PM
-
Wednesday, February 29, 2012 5:33 PM
Are you trying to access the items in code behind?
<Menu Name="menu"> <MenuItem Header="File"> <MenuItem Header="Open"/> <MenuItem Header="New"/> </MenuItem> </Menu>
var menuItem = (MenuItem)menu.Items[0]; menu.MouseDown += new MouseButtonEventHandler(menu_MouseDown);This works for me, Let me know if your problem is misunderstood.
Hope it helps!
Regards Vallarasu S. FSharpMe.blogspot.com
- Edited by VallarasuS Wednesday, February 29, 2012 5:36 PM improved
- Edited by VallarasuS Wednesday, February 29, 2012 5:37 PM improved
-
Wednesday, February 29, 2012 6:21 PMThank you! I have solved it now :)

