Creating a context menu

Context menus are typically invoked when the user right clicks a certain area or element (or presses Shift + F10 or a designated key on some keyboards). They are called "context" menus because different situations may call for different menus, or at least different available options. The ContextMenu class (a derivative of MenuBase) can host a bunch of MenuItem controls (and separators). Let's see how this works.

Getting ready

Open the CH04.Lists project from the Creating a list of items recipe.

How to do it…

We'll continue with the CH04.Lists project and enhance it to make a context menu available:

  1. Open MainWindow.xaml.
  2. Set the ContextMenu property of the ListBox to a ContextMenu object with some MenuItem instances:
    <ListBox.ContextMenu> ...

Get Windows Presentation Foundation 4.5 Cookbook now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.