Click here to Skip to main content
15,888,070 members
Articles / Silverlight / Silverlight5

Custom ContextMenu in Silverlight Applications

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
21 Aug 2012CPOL3 min read 25K   4   1
In this simple tutorial, I want to show how to hide the default Context Menu presents on every Silverlight application created via Visual Studio.

In every Silverlight application, we have a context menu with two elements inside, one of them corresponding to the information of Silverlight’s version installed on the current computer. The other one allows to install a Silverlight Business Application (not available on this tutorial).

Because we only apply an Web Site implementation, don’t have the “Install Silverlight Application” option. This option is only available on a Silverlight Business Application where we can install and uninstall the Silverlight application from the desktop. Silverlight Business Application allows two ways of implementation: In the browser and Out of the browser (just like a desktop application).

Obviously, the first step is to create a new Silverlight Application, selecting the option of Web Site (on the DropDownList). Or, if you prefer, you can add this functionality on your current project.

At this point, we have our default files and folders. We focused on MainPage files (.xaml and .xaml.cs). To avoid confusion, we delete the aspx file on Web Site project, we don’t need on this tutorial.

On your MainPage.xaml page, put these lines of code:

XML
<UserControl x:Class="CustomContextMenu.MainPage"
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
 Height="200" Width="350">

<Grid x:Name="LayoutRoot" Background="Azure">
 <TextBlock Text="Context Example" FontFamily="Arial" 
 FontSize="12" FontWeight="Bold" />
 </Grid>
</UserControl>

Run the project (F5). Don’t forget to mark the Web Site as startup project! Here, Visual Studio asks if we want to modify the web.config or not. Just leave the default option.

Well, after we do all of these steps, we have an empty project with Azure background and a simple textblock, for testing purposes is OK. By default, our little Silverlight will have a context menu that show “Silverlight“.

Go back to the Visual Studio and stop the running project. Now we are going to focus on MainPage.xaml.cs.

Ok, now we are going to disable that context menu from Silverlight Application. For doing this, we need to write some code (inside your MainPage.xaml.cs file), just like this:

C#
//Constructor of the Main Page
 public MainPage()
 {
 // Initialize all Visual components
 InitializeComponent();

// Add the Mouse Right click Event Handler
 this.MouseRightButtonDown += (s, e) =>
 {
 //Mark the routed event as handled to disable the default context menu.
 e.Handled = true;
 };
 }

The code above creates a mouse right button event handler. So, when we right click on any place inside the Silverlight application, we must cancel the event. Really, we handle the event saying to the compiler “leave this, I have control of this event!”.

All right, but the main title talks about “Custom ContextMenu”. The fragment below talks about that. But I think that was useful for many of you. Now, the last thing that I can tell you is that if you want to implement that behavior, you must need to copy/paste the C# code inside all Constructors of any Page in your Silverlight Page (In a few days, I will implement another way to do this).

Now, we focused on the main title of this tutorial. We’ll create a new contextual menu independent from the default one (you can add background, forecolor, and all you want on XAML).

For creating a new context menu, we need to write the following lines on our MainPage.xaml file, just like this:

XML
<UserControl x:Class="CustomContextMenu.MainPage"
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
 Height="200" Width="350"
 xmlns:contextMenu="clr-namespace:System.Windows.Controls;
 assembly=System.Windows.Controls.Input.Toolkit">

<Grid x:Name="LayoutRoot" Background="Azure">
 <TextBlock Text="Context Example" FontFamily="Arial" 
 FontSize="12" FontWeight="Bold" />
 <contextMenu:ContextMenuService.ContextMenu>
 <contextMenu:ContextMenu>
 <contextMenu:MenuItem Header="Contextual Menu 1" />
 <contextMenu:Separator />
 <contextMenu:MenuItem Header="Contextual Menu 2" 
 Click="MenuItem_Click" />
 </contextMenu:ContextMenu>
 </contextMenu:ContextMenuService.ContextMenu>
 </Grid>
</UserControl>

Sure, many of you have some error in your XAML saying “We can’t find the namespace…”. To fix errors, just don’t forget to Add References to System.Windows.Controls and System.Windows.Controls.Input.Toolkit namespaces.

Now, in your MainPage.xaml.cs (You can press F7 key for direct access to code behind) and add this line of code:

C#
private void MenuItem_Click(object sender, RoutedEventArgs e)
 {
 //Show a simple message on Silverlight Application
 MessageBox.Show("You clicked on Contextual Menu 2!");
 }

Remember that you can create really beautiful contextmenu if you play with some elements inside your XAML. I can tell you that XAML allows some really nice alternatives to do fantastic applications. All we have to do is take our Visual Studio and play with some features available inside it. C# is a powerful language but we can replace some lines of code with XAML adoption. Sure, depends on you.

That was a very simple tutorial about ContextMenu on Silverlight 5. This implementation is very useful if you need to present alternatives for the user that consume your application. It’s very simple to right click and have a quick access to main features for a determinate scenario. Hope you can comment on this article to show me another way or another example of contextmenu.

Hope you can find this article useful. :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
Paraguay Paraguay
hristian Amado is a professional software engineer, professional developer and trainer with over 18 years of experience building applications for Windows Desktop and the Web. Located in Asuncion, Paraguay, He's well involved in many Microsoft's technologies including XAML, C#, X++, WCF, ADO.NET and ASP.NET.

He holds a several Microsoft certifications including Microsoft Certified Professional Developer (MCPD), Microsoft Certified IT Professional, Microsoft Certified Technology Specialist and Microsoft Office Specialist.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Dulce Barrios5-Sep-12 16:31
Dulce Barrios5-Sep-12 16:31 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.