Right Click and Context Menu In Silverlight 4

Download Source


Right Click, one of the awaiting features in Silverlight 4. In addition Silverlight 4 Toolkit contains Context Menu control. In this article we will see how we can use Context Menu to be displayed on Right Click in Silverlight 4.

Creating Silverlight Project

Fire up Visual Studio 2010 and create a new Silverlight Application Project. Name it as ContextMenuSample.


Let’s add the following assembly references to use the ContextMenu and MenuItem. These are included in current version of Silverlight 4 Toolkit.


Now, let’s design the page. We will have a TextBox. On Right Click the context menu will be displayed. In the context menu we will have two menus such as Grow Font and Shrink Font. Based on the selection the font size of the TextBox would change.

Now let’s add the two important events such as MouseRightButtonDown and MouseRightButtonUp. These two events will help us displaying the ContextMenu.

In the MouseRightButtonDown we need to Handle it to disable the default Silverlight Menu.

Now the default Silverlight settings menu would not be displayed for TextBox. However it can be seen if we right click on other UIElement.

In MouseRightButtonUp we will create ContextMenu and display it.

As you see in above code, we are creating two MenuItems and subscribing it’s Click event. Finally we are setting the IsOpen property to true to display the Context menu.

The position of the ContextMenu should be relative to the LayoutRoot, so we are setting the HorizontalOffset and VerticalOffset relative to the LayoutRoot’s X and Y properties.


Now we will handle the Click event of the MenuItem to fulfill our objective and that is Grow and Shrink the font size of the TextBox.

Now we are ready to have a test drive.

Based on our selection the Grow and Shrink would work.

That’s it. Hope this article helps.