C# WPF Tutorial – ContextMenu

0
775
C# WPF Tutorial – ContextMenu

WPF ContextMenu is a kind of popup which is used to provide features based on events or context on any WPF Control. It is only exposed when the user trigger context from UI.

To make it very clear we are going to add ContextMenu for WPF Button. Just for reference, RoutedCommand is also similar to this but not exactly this.

In the following XAML Code, we added the Simple WPF Button. Then inside the button, we are declaring Context, and then inside that, we are defining ContextMenu along with MenuItem.

XAML Code:

<Button Content="ContextMenu Example">
<Button.ContextMenu>
<ContextMenu>
<MenuItem Header="Any_Event_Which_You_Want_1"/>
<MenuItem Header="Any_Event_Which_You_Want_2"/>
</ContextMenu>
</Button.ContextMenu>
</Button>

Remember, all the WPF component is eligible for Context, meaning you can apply the same logic to all WPF UI Components. The context will trigger whenever the user will right-click on the component or the area of the component. As in our case, we created a button and when we right-click on any button area we will get the menu with the above item listed on the xaml code.

Output:

C# WPF Tutorial – Contextmenu Example 1

This image is showing the output of the xaml code. Right now these items are purposeless because we just declared not defined what will happen on click. So we will add an event listener also, you can add any event listener and we are adding click event only.

XAML Code For Event:

<Button Content="ContextMenu Example">
<Button.ContextMenu>
<ContextMenu>
<MenuItem Header="Any_Event_Which_You_Want_1" Click="MenuItem_Click"/>
<MenuItem Header="Any_Event_Which_You_Want_2"/>
</ContextMenu>
</Button.ContextMenu>
</Button>

Now whenever a user will click on Item 1, the respective event listener will trigger and based on that you can write your business logic.

For example, you want to change the text of the button whenever the user clicks on the item menu. This will be done by the following code.

private void MenuItem_Click(object sender, RoutedEventArgs e)
{
ExampleButton.Content = "Any_Event_Which_You_Want_1";
}

Output As Gif:

If you are still confused and have any issues regarding your application feel free to contact me.