Right Click a TextBox and Display a ContextMenu using Silverlight 4

Posted by: Suprotim Agarwal , on 5/21/2010, in Category Silverlight 2, 3, 4 and 5
Views: 73359
Abstract: In versions prior to Silverlight 4, when you right clicked an UI Element, the events were handled by the Silverlight plug-in internally to display the Silverlight configuration dialog
In versions prior to Silverlight 4, when you right clicked an UI Element, the events were handled by the Silverlight plug-in internally to display the Silverlight configuration dialog. In Silverlight 4, you now have the ability to right click an element and invoke a custom ContextMenu. Silverlight 4 now adds support for MouseRightButtonDown and the MouseRightButtonUp events on all UIElements. The Silverlight Toolkit (April Release) also introduces the ContextMenu control to Silverlight developers. In this article, we will see how to
-      Use the ContextMenu control released in the Silverlight 4 Toolkit
-      Display the ContextMenu on a TextBox by using the new Right-Click mouse event support in Silverlight 4
-      Access the clipboard programmatically (new in Silverlight 4) to do Cut, Copy and Paste operations on a TextBox
Make sure you are using the latest Silverlight toolkit over here. Let us get started:
Step 1: Create a new Silverlight 4 application. Open VS2010 > File > New Project > Silverlight Application
Step 2: Add a TextBox and a ContextMenu control from the Toolbox. The markup will look similar to the following:
<UserControl xmlns:toolkit="http://schemas.microsoft.com/winfx/2006/xaml/presentation/toolkit"  x:Class="SilverlightRightMouseClick.MainPage"
    d:DesignHeight="300" d:DesignWidth="400">
    <Canvas x:Name="LayoutRoot" Width="450" Height="400" Background="White">
        <TextBox x:Name="tb" Text="Select Text and Right Click"/>
            <toolkit:ContextMenu Name="cm">
                <toolkit:MenuItem Header="Cut" Click="MenuItem_Click"/>
                <toolkit:MenuItem Header="Copy" Click="MenuItem_Click"/>
                <toolkit:MenuItem Header="Paste" Click="MenuItem_Click"/>
Note: You may have observed that we have used the ContextMenuService.ContextMenu attached property. The reason for it is in WPF, you could use the FrameworkElement.ContextMenu property to attach a ContextMenu to an element. However this property is not supported in Silverlight. Hence the ContextMenuService.ContextMenu provides a similar functionality.
The ContextMenu control contains 3 menu items bound to MenuItem_Click
Step 3: Let us code the MenuItem_Click method in MainPage.xaml.cs/vb
private void MenuItem_Click(object sender, RoutedEventArgs e)
    MenuItem menuItem = (MenuItem)sender;
    switch (menuItem.Header.ToString())
        case "Cut":
            tb.SelectedText = "";
        case "Copy":
        case "Paste":
            tb.SelectedText = Clipboard.GetText();
    cm.IsOpen = false;
Private Sub MenuItem_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
      Dim menuItem As MenuItem = CType(sender, MenuItem)
      Select Case menuItem.Header.ToString()
            Case "Cut"
                  tb.SelectedText = ""
            Case "Copy"
            Case "Paste"
                  tb.SelectedText = Clipboard.GetText()
            Case Else
      End Select
      cm.IsOpen = False
End Sub
In the code shown above, we are programmatically accessing the clipboard when a menu item of the ContextMenu is clicked to do Cut, Copy and Paste operations on the TextBox. Here’s what the code does
Clipboard.SetText() - Copies data from a Silverlight application to the clipboard
Clipboard.GetText()- Retrieves copied date from the clipboard
tb.SelectedText = Clipboard.GetText()- Does a copy and paste. To do a Cut operation, just use the Clipboard.SetText() and set the content of the current selection to an empty string
Step 4: The last part is to implement the right-click and display the ContextMenu on the TextBox. To do so, just handle the MouseRightButtonDown event and set the MouseButtonEventArgs.Handled property to true.
public MainPage()
    tb.MouseRightButtonDown += new MouseButtonEventHandler(tb_MouseRightButtonDown);
    tb.MouseRightButtonUp += new MouseButtonEventHandler(tb_MouseRightButtonUp);
void tb_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
    cm.HorizontalOffset = e.GetPosition(tb).X + 2;
    cm.VerticalOffset = e.GetPosition(tb).Y + 2;
    cm.IsOpen = true;
void tb_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
    e.Handled = true;
Public Sub New()
      AddHandler tb.MouseRightButtonDown, AddressOf tb_MouseRightButtonDown
      AddHandler tb.MouseRightButtonUp, AddressOf tb_MouseRightButtonUp
End Sub
Private Sub tb_MouseRightButtonUp(ByVal sender As Object, ByVal e As MouseButtonEventArgs)
      cm.HorizontalOffset = e.GetPosition(tb).X + 2
      cm.VerticalOffset = e.GetPosition(tb).Y + 2
      cm.IsOpen = True
End Sub
Private Sub tb_MouseRightButtonDown(ByVal sender As Object, ByVal e As MouseButtonEventArgs)
      e.Handled = True
End Sub
The ContextMenu.IsOpen sets a value to make the ContextMenu visible.
That’s it. Run your application and you should be able to invoke the ContextMenu on right-click and perform Cut, Copy and Paste operations on the TextBox.
Note: When you programmatically access the clipboard for the first time, Silverlight will prompt the user with a dialog to request permission to access the clipboard. Click Yes.
I hope you liked the article and I thank you for viewing it. The entire source code of this article can be downloaded over here

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for ten consecutive times. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn

Page copy protected against web site content infringement 	by Copyscape

Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Moshe on Wednesday, January 26, 2011 11:46 AM
The Part 4 is redundant.
Comment posted by junior jack on Thursday, January 27, 2011 6:07 AM
I would like to have an working example of this with MVVM
Comment posted by Mark Kamoski on Wednesday, February 9, 2011 2:47 PM
Suprotim  -- This is a GREAT article. It helped a lot. It was driving me bonkers trying to get right-click to work in Silverlight 4. Now, I can do cut and copy and paste with ease. Thank you SO much!!! -- Mark Kamoski
Comment posted by Suprotim Agarwal on Friday, February 11, 2011 6:28 AM
Glad it helped you Mark :)
Comment posted by JB_ on Wednesday, February 16, 2011 12:42 PM
Thx a lot! i spend a lot of time to try do this in my uni project. Once again THANK YOU!!:)
Comment posted by twincle on Wednesday, May 30, 2012 12:09 PM
We will not give any votes / feedback to cheaters...
Comment posted by hoffu on Friday, June 1, 2012 5:16 AM
cheaters? Who Silverlight ;)
Comment posted by steph on Tuesday, February 10, 2015 9:27 AM
wow 5 years later this helped me out :)