Javatpoint Logo
Javatpoint Logo

WPF Context Menu

Context Menu, usually known as the popup or the popup menu, will show when the user performs a particular action. Usually, the context menu will appear when we do the right-click with the mouse on the specific control or window.

WPF contains the context-menu control because the context menu always tied to the specific control. This shows us how we can add the Context-menu to the interface.

Context Menu inherits the MenuBase class.

Now we will write the XAML code to add the context menu in WPF.

MainWindow.XAML

The output of the above code is shown below:

OUTPUT

WPF Context Menu

Now we will do the right-click on the button after clicking on the window Context-Menu:

WPF Context Menu

When we use the Context-Menu now, we will use the concepts of the two-key.

WPF command provides us the different functionality, which includes the event-handling on the click, text, and the shortcut text. After assigning the command property, we will write the XAML code for the event handling.

MainWindow.XAML

In the initial state, the output of the above code will show us like as shown in the below screenshot:

OUTPUT

WPF Context Menu

After right-clicking on the text, the output of the above code is shown in the below screenshot:

WPF Context Menu

After right-clicking on the text, a popup is shown to us containing the functionality of cut, copy, and paste command.

We see how simple it is to use the icons on to the menu items of the context menu from the above screenshot.

Invoke the ContextMenu with the help of the code

Before this, we have seen that we invoked the ContextMenu after the right-clicking on the control. With the help of the WPF, we invoked the context menu automatically when we assign it to the ContextMenu property. But there is the situation that arises when we want to invoke the ContextMenu manually with the help of the code.

For this we will write the below code:

MainWindow.XAML

Event Button_Click has occurred. On the MainWindow.XAML.cs, we will do the coding in C#.

MainWindow.XAML.CS

OUTPUT

WPF Context Menu

The button is having the click event handler, which is handled in the source code. Window resources contain the object of the context situated in window Resources.






Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA