Tutorials » Silverlight tutorials »

How to display custom Rightclick context menu in Silverlight controls?

This sample shows how to intercept the default context menu and display a custom context menu in a Silverlight control

When you right click on any Silverlight controls in a web page, it display the default Silverlight context menu which with a single option view the Silverlight Configuration. You may intercept this context menu and display your own menu.

The first step you have to do is, go to the aspx page where you are hosting the Silverlight control and set the property "Windowless" to "True"

<asp:Silverlight ID="Xaml1"
Width="100%" Height="100%" />

Now, you can use the "AttachEvent" property of the browsers Document object to attach your own event handler to the "oncontextmenu" event from your xaml pages.

Sample code:

System.Windows.Browser.HtmlPage.Document.AttachEvent("oncontextmenu", this.OnContextMenu);

You may attach your event handler from the constructor of your XAML page. You can even do this from the constructor of your App.xaml, in which case the event handler will be triggered from every xaml page you use in the project.

And here is the code to handle the event:

private void OnContextMenu(object sender, System.Windows.Browser.HtmlEventArgs e)
MessageBox.Show("You click at " + e.OffsetX + "," + e.OffsetY);


The above code sample displays the coordinates you clicked. You may replace that code to display your own menu or popup window.

The code e.PreventDefault();" prevents the events from being propagated to other child controls

You can download a sample project for this tutorial.

Next Chapter: Introduction to DataBinding in Silverlight
Previous Chapter: How to play audio or sound files from Silverlight
More Chapters: Silverlight Tutorials
More Tutorials: Tutorial Index

Top Contributors
    Last 7 Daysmore...

    Awards & Gifts

    Online Members

    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India