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">

 <StackPanel
    VerticalAlignment="Top">
    <StackPanel
       Orientation="Horizontal">
       <TextBlock
          Text="last selection:"
          Style="{StaticResource PhoneTextSubtleStyle}" />
       <TextBlock
          Text="none"
          x:Name="lastSelection"
          Style="{StaticResource PhoneTextNormalStyle}" />
    </StackPanel>

    <Button
    Margin="0,40"
    VerticalAlignment="Center"
    Padding="12"
    Content="ContextMenu"
    FontSize="18">

 

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

 <toolkit:ContextMenuService.ContextMenu>
   <toolkit:ContextMenu>
      <toolkit:MenuItem
         Header="this is a menu item"
         Click="MenuItem_Click" />
      <toolkit:MenuItem
         Header="this is another menu item"
         Click="MenuItem_Click" />
      <toolkit:MenuItem
         Header="this is a yet another menu item"
         Click="MenuItem_Click" />
   </toolkit:ContextMenu>
 </toolkit:ContextMenuService.ContextMenu>
</Button>

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 online courses. His latest book, Building APIs with .NET will be released early in 2025. Liberty is a Senior SW Engineer for CNH and 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 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.