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: 51685
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
NewProject
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"
    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"
    mc:Ignorable="d"
    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:ContextMenuService.ContextMenu>
            <toolkit:ContextMenu Name="cm">
                <toolkit:MenuItem Header="Cut" Click="MenuItem_Click"/>
                <toolkit:MenuItem Header="Copy" Click="MenuItem_Click"/>
                <toolkit:Separator/>
                <toolkit:MenuItem Header="Paste" Click="MenuItem_Click"/>
              </toolkit:ContextMenu>
          </toolkit:ContextMenuService.ContextMenu>
    </Canvas>
</UserControl>
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
C#
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
    MenuItem menuItem = (MenuItem)sender;
    switch (menuItem.Header.ToString())
    {
        case "Cut":
            Clipboard.SetText(tb.SelectedText);
            tb.SelectedText = "";
            tb.Focus();
            break;
        case "Copy":
            Clipboard.SetText(tb.SelectedText);
            tb.Focus();           
            break;
        case "Paste":
            tb.SelectedText = Clipboard.GetText();
            break;
        default:
            break;
    }
    cm.IsOpen = false;
}
 
VB.NET
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"
                  Clipboard.SetText(tb.SelectedText)
                  tb.SelectedText = ""
                  tb.Focus()
            Case "Copy"
                  Clipboard.SetText(tb.SelectedText)
                  tb.Focus()
            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.
C#
public MainPage()
{
    InitializeComponent();          
 
    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;
}
 
VB.NET
Public Sub New()
      InitializeComponent()
 
      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.
MicrosoftSilverlight
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
Give me a +1 if you think it was a good article. Thanks!
Recommended Articles
Suprotim Agarwal, ASP.NET Architecture MVP, MCSD, MCAD, MCDBA, MCSE, is the CEO of A2Z Knowledge Visuals Pvt. He primarily works as an Architect Consultant and provides consultancy on how to design and develop .NET centric database solutions.

Suprotim is the founder and primary contributor to DotNetCurry, SQLServerCurry and DevCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal




Page copy protected against web site content infringement by Copyscape


User Feedback
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 09, 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 01, 2012 5:16 AM
cheaters? Who Silverlight ;)

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel