Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In WPF how to add menu item event?

In my WPF application, I add a menu then add several menu items under it. For example, one of my menu item is "Main Item", then I add subItem1, subItem2 and subItem3 under "Main Item". I want to click subItem1 and do something(e.g. MessageBox.show a message). Why I cannot find the event for this subItem1? How can I add the click event for subItem1? I find the property for subItem1 under the collection property for "Main Item", but can only see property, cannot see event list. How can I add click event for subItem1? Thank you!

like image 321
spspli Avatar asked Mar 29 '11 21:03

spspli


People also ask

What is context menu WPF?

A ContextMenu is attached to a specific control. The ContextMenu element enables you to present users with a list of items that specify commands or options that are associated with a particular control, for example, a Button. Users right-click the control to make the menu appear.

What .NET WPF class we use to create menus which namespace it belongs to?

WPF Menu control is represented by the Menu class in C#. This menus tutorial and menus code examples explain how to use menus in WPF using C#. In WPF, the Menu and the MenuItem classes represent a menu and a menu item respectively. A Menu is a collection of menu items with a command associated with each menu item.

What is event Handler WPF?

You can assign an event handler to an element in Windows Presentation Foundation (WPF) using markup or code-behind. Although it's customary to assign an event handler in Extensible Application Markup Language (XAML), sometimes you might have to assign an event handler in code-behind.


1 Answers

In your xaml:

<Menu IsMainMenu="True">
<MenuItem Header="MainMenu">
<MenuItem Header="subItem1" 
 x:Name="subItem1" Click="subItem1_Click">
</MenuItem>
</MenuItem>
</Menu>

In your code-behind:

private void subItem1_Click(object sender, RoutedEventArgs e)
{

}
like image 159
dugas Avatar answered Sep 18 '22 18:09

dugas