Adding right-click functionality in Silverlight 4

24 11 2009

Not having the right mouse button available has been a hassle for both Silverlight and Adobe Flash since their inception. Flash has had the ability to customize their right-click context menu to some degree but never true right click event handling. With Silverlight 4, Silverlight will have true customizable event handling for the right mouse button. I know this might be a small step for event handling, but it’s a giant leap for rich Internet applications.

SmallStepForEventHandling

To do this in Silverlight 4, this is the code you’ll need to use:

We’re going to add an eventhandler first to out main window and then to a control through XAML.

//For a general rightclick menu for your window

this.MouseRightButtonDown += new MouseButtonEventHandler(MainPage_MouseRightButtonDown);
this.MouseRightButtonUp += new MouseButtonEventHandler(MainPage_MouseRightButtonUp);

void MainPage_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
//This is crucial. If you don’t add this, the original context menu will always show up on rightclick.
e.Handled = True;
}

void MainPage_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
{
MessageBox.Show(“Hello, Brave New World!”);
}

This can of course be used on different objects with different effects and if we want to add an event handler in XAML instead, this is the code we’ll use within an object (such as a Grid):

MouseRightButtonDown=”MainPage_MouseRightButtonDown”

MouseRightButtonUp=”MainPage_MouseRightButtonUp”

The possibilities are many and I’m glad to be using a technology that is constantly improving.

Advertisements

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: