In today’s article, we’ll be looking at another new feature that was added with Silverlight 4, namely the ability to react to right-clicks in a Silverlight application. This means that we can override the default behavior of Silverlight where it’s showing the context menu allowing us to go to the configuration screen.
Because Silverlight now supports right-clicking, we can create a context menu that appears on the right-click event. We can code this context menu as we want. Right-clicking is supported on any UIElement: on the UIElement class, there are two new events added, namely the MouseRightButtonDown and the MouseRightButtonUp. Both of these new events use MouseButtonEventArgs as their event arguments, which are also used for the normal left click events.
As said, by default, the Silverlight context menu is shown when a user right-clicks on a Silverlight application. To block this, in the MouseRightButtonDown, we have to set the e.Handled to true. This way, the default context menu is not shown and we can go ahead and create our own context menu. This will appear on the MouseLeftButtonUp event.
Let’s take a look at a simple application. In this application, we have attached a custom context menu on an Image control. Using this context menu, I can choose to delete the image I clicked on.
The image itself has both the MouseRightButtonDown and the MouseRightButtonUp events attached to it using XAML code:
<Image Height="195" x:Name="imgTree" Stretch="Fill" Width="249"
MouseRightButtonDown="imgTree_MouseRightButtonDown"
MouseRightButtonUp="imgTree_MouseRightButtonUp"
Source="tree.png" Canvas.Left="181" Canvas.Top="79">
</Image>
To prevent the default context menu from appearing, we can set the e.Handled to true in the mouse down event:
private void imgTree_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
e.Handled = true;
}
In the mouse up event, we can then specify what context menu we want to have appear:
private void imgTree_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
Image image = sender as Image;
if (image != null)
ContextMenu contextMenu = new ContextMenu(PrintCanvas, image);
contextMenu.Show(e.GetPosition(LayoutRoot));
The ContextMenu used here is a custom control.
The complete source code can be downloaded here: SLRightClick.zip (473.2 KB)
Ads by The Lounge
All content is property of www.snowball.be. Nothing on this site can be copied or published elsewhere, unless otherwise stated.
This site is made by Gill Cleeren.
Questions? Opinions? E-mail