23

How can I open menu (System.Windows.Controls.Menu) programmatically in WPF?

5 Answers 5

29

Get hold of the menu item, and do this :

_menuItem.IsSubmenuOpen = true; 
Sign up to request clarification or add additional context in comments.

Comments

28

Check out this example on how to open a context menu.

http://www.uxpassion.com/2009/01/how-to-enable-and-show-context-menu-on-left-click-in-wpf/

In summary

You can just call:

YourContextMenu.IsOpen = true; 

This will display the context menu, just make sure its associated with a FrameworkElement on which it is displaying)

3 Comments

No, the OP is asking about the Menu class (System.Windows.Controls.Menu). It doesn't have an IsOpen property. Perhaps you are thinking of the ContextMenu class.
You will also need to initialize YourContextMenu.PlacementTarget with intended "target" UIElement. Otherwise, the menu constructed dynamically from XAML string (using XamlReader) will not be able to resolve resources, and will have no icons, for example.
What also helps is listening to ContextMenu.Opened and then calling CnotextMenu.Focus() to ensure that it receives keyboard input, e.g. to ensure the ESC key is handled by the context menu (to close it) and that arrow keys can be used for navigation.
4
private void button_Click(object sender, RoutedEventArgs e) { var button= sender as FrameworkElement; if (button != null) { button.ContextMenu.IsOpen = true; } } 

Comments

1
 private void MainGrid_Loaded(object sender, RoutedEventArgs e) { IncList.ItemsSource = m_DataSource; IncList.ContextMenu = new ContextMenu(); IncList.ContextMenu.Items.Add(new MenuItem() { Header = "Test1" }); IncList.ContextMenu.Items.Add(new MenuItem() { Header = "Test2" }); } 

Comments

0
void CmsBox_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { box = sender as WpfBox; ContextMenu cms = new ContextMenu(); e.Handled = true; ... } 

Comments