Hosting a ContextMenu in a ListBoxItem

Sometimes the need arises to provide a context menu for dynamically generated elements, such as those presented using a data bound ItemsControl. The following example demonstrates how to host a context menu for each item in a ListBox.

The ContextMenuViewModel contains an ObservableCollection of strings, declared as shown:

readonly ObservableCollection<string> items                  = new ObservableCollection<string>();public IEnumerable<string> Items{    get    {        return items;    }}

The items collection is populated within the viewmodel constructor. In addition, a new command, named DeleteCommand, is placed in the viewmodel. When the command is executed, it removes the ...

Get Windows® Phone 8 Unleashed now with the O’Reilly learning platform.

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