Let us see the procedure for opening a Context Menu in Windows Phone 8. Create a new project with a valid name, once everything is ready our project looks as in the following screen.
Now add one TextBlock control to the triggers and show the context menu, change the TexxtBlock content to “Open Context Menu”.
Next add a reference for Microsoft.Phone.Controls.Toolkit.dll to your project. You can get this DLL in the following URL.
Now add the following namespace in the XAML page.
xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
XAML Code
- <phone:PhoneApplicationPage
- x:Class="ContextMenuDemo.MainPage"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
- xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
- xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
- xmlns:c4fToolkit="clr-namespace:Coding4Fun.Phone.Controls;assembly=Coding4Fun.Phone.Controls"
- mc:Ignorable="d"
- FontFamily="{StaticResource PhoneFontFamilyNormal}"
- FontSize="{StaticResource PhoneFontSizeNormal}"
- Foreground="{StaticResource PhoneForegroundBrush}"
- SupportedOrientations="Portrait" Orientation="Portrait"
- shell:SystemTray.IsVisible="True">
-
- <Grid x:Name="LayoutRoot" Background="Transparent">
- <Grid.RowDefinitions>
- <RowDefinition Height="Auto"/>
- <RowDefinition Height="*"/>
- </Grid.RowDefinitions>
- <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
- <TextBlock Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
- </StackPanel>
- <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
- <TextBlock TextWrapping="Wrap" Text="Open Context Menu" Margin="98,218,129,441" FontSize="24">
- <toolkit:ContextMenuService.ContextMenu>
- <toolkit:ContextMenu Name="ctxMenuRoster">
- <toolkit:MenuItem Header="option1" Click="MenuItem_Click"/>
- <toolkit:MenuItem Header="option2" Click="MenuItem_Click_1"></toolkit:MenuItem>
- </toolkit:ContextMenu>
- </toolkit:ContextMenuService.ContextMenu>
- </TextBlock>
- </Grid>
- </Grid>
- </phone:PhoneApplicationPage>
The following is the sample code snippet to implement a context menu in Windows Phone 8.
Here, I implemented two menu options, option1 and option2. This menu will open when we long press the TextBlock.
Run the application by pressing the F5 Key and see the output as shown in the following. Using a long press of the “Open Context Menu” TextBlock we get the excepted output.