by brad
2. November 2010 06:00
Today’s tip focuses on the ContextMenu that’s available in the Silverlight Toolkit for Windows Phone. If you’re not familiar with the Toolkit, check out the introductory post.
Context Menus on Windows Phone 7
The context menu is an easy concept to understand because it’s baked into several places in the Windows Phone operating system. One place you can see it is in the application list. If you tap and hold one of the application icons, you’ll see a context menu appear.
![CropperCapture[18] CropperCapture[18]](http://www.codebadger.com/blog/image.axd?picture=CropperCapture%5B18%5D.jpg)
In the screenshot above, you can see the context menu that appears when tapping and hold the Internet Explorer icon. This is the phone equivalent of a right-click menu and appears, like in the application list, by tapping and holding.
Implementing your own context menu
To use the context menu, first add a reference to Microsoft.Phone.Controls.Toolkit.dll, which is installed with the toolkit.
Next, add a reference to the assembly in your page XAML
1: xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
2: xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
3: mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
The XAML for adding a context menu looks like this:
1: <Button Content="Big Button">
2: <toolkit:ContextMenuService.ContextMenu>
3: <toolkit:ContextMenu>
4: <toolkit:MenuItem Header="share" Tag="share" Click="MenuItem_Click" />
5: <toolkit:MenuItem Header="delete" Tag="delete" Click="MenuItem_Click" />
6: <toolkit:MenuItem Header="favorite" Tag="favorite" Click="MenuItem_Click" />
7: </toolkit:ContextMenu>
8: </toolkit:ContextMenuService.ContextMenu>
9: </Button>
This creates a big button that is ready for tap-and-hold. When the users taps and holds, the context menu appears. The Header property determines the text for each menu item, and the Tag property can be used to send additional information for the event handler. Alternatively, you could map each menu item to its own event handler. In this case, they are all mapped to MenuItem_Click.
![CropperCapture[19] CropperCapture[19]](http://www.codebadger.com/blog/image.axd?picture=CropperCapture%5B19%5D.jpg)
In this simple example, MenuItem_Click is just reading the Tag property and spitting it back to show that everything is wired up correctly.
1: private void MenuItem_Click(object sender, RoutedEventArgs e)
2: {
3: var menuItem = (MenuItem) sender;
4: var tag = menuItem.Tag.ToString();
5: MessageBox.Show(tag);
6: }
![CropperCapture[20] CropperCapture[20]](http://www.codebadger.com/blog/image.axd?picture=CropperCapture%5B20%5D.jpg)
Other Resources
More Tips