Context Menu

Windows Phone Tutorial

The Silverlight For Windows Phone Toolkit is a magnificent collection of controlsContextMenu and utilities for writing Windows Phone applications.  Unfortunately, there is little or no documentation, and the samples, while wonderful, are quite complex.  At times, it is difficult to tease out how to use a control; how to “just make it work.”

As I have done in previous mini-tutorials, this posting will show one of the toolkit controls stripped down to its bare essentials.  Creating a context menu, and responding to the user’s choice in the menu turns out to be wicked easy.

To get started, create a new Mango application.  On MainPage we’re going to add a StackPanel which in turn will hold two things:

  • An inner StackPanel to show the menu choice
  • A button which will have a context-menu.
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">

          Text="last selection:"
          Style="{StaticResource PhoneTextSubtleStyle}" />
          Style="{StaticResource PhoneTextNormalStyle}" />



Within the declaration of the button we’ll declare a ContextMenu

         Header="this is a menu item"
         Click="MenuItem_Click" />
         Header="this is another menu item"
         Click="MenuItem_Click" />
         Header="this is a yet another menu item"
         Click="MenuItem_Click" />

That’s all there is to it, except handling the click of a Menu item.  All we want to do, in this case, is ask the sender for its text, and display that in the TextBlock above the button.  Here’s the code:

private void MenuItem_Click( object sender, RoutedEventArgs e )
    lastSelection.Text =  
        ((( MenuItem ) sender).Header).ToString();

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen Pluralsight & LinkedIn Learning courses. He was a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Xamarin Certified Mobile Developer and a Xamarin MVP and a Microsoft MVP.
This entry was posted in Essentials, Mango, Mini-Tutorial, Patterns & Skills, Toolkit, WindowsPhone and tagged . Bookmark the permalink.

One Response to Context Menu

Comments are closed.