Silverlight 4 Right-click mouse support

Silverlight 4Silverlight 4 (currently in beta) adds support for right-click mouse events on all UIElements:

  • MouseRightButtonDown
  • MouseRightButtonUp

In Silverlight 3 those events were not exposed and used internally by the plug-in to show the Silverlight context menu. With Silverlight 4 the default behaviour is still like in Silverlight 3 (Silverlight context menu) but now if you want you can override this and provide your own context menu.

In fact you just need to handle the events above and build you custom UI (no, there is no template for context menu in the beta), AND you need to mark the MouseRightButtonDown event as handled (e.Handled = true), if you forget you will get the default context menu.

In my sample I use a ColorPicker control in a xaml popup to change the Rectangle’s Fill property with the selected color via right click:

Silverlight 4 right click sample

The XAML has just a Rectangle and a Popup with a ColorPicker:

<TextBlock Text="Customize this shape with right-click" FontWeight="Bold" Margin="12,0,0,0"/>

<Rectangle Height="254" HorizontalAlignment="Left" Margin="12,24,0,0"
Name="frame" Stroke="Black" StrokeThickness="4" VerticalAlignment="Top"
Width="320" RadiusX="15" RadiusY="15" Fill="Red"
MouseRightButtonUp="frame_MouseRightButtonUp" /> <Popup x:Name="pop"> <Border Background="LightBlue" Margin="10" BorderBrush="Blue" CornerRadius="5" BorderThickness="3"> <StackPanel Width="220" Height="240"> <TextBlock Text="Pick a new color:" FontWeight="Bold" HorizontalAlignment="Center"/> <my:ColorPicker HorizontalAlignment="Left" x:Name="colorPicker1" Margin="10" /> StackPanel> Border> Popup>

In CodeBehind:

– I mark the MouseRightButtonDown as handled

– I open the popup on MouseRightButtonUp and position its HorizontalOffset and VerticalOffset close to the mouse location with GetPosition method.

– When a color is selected I close the popup and fill the Rectangle with it.

public MainPage()

    colorPicker1.ColorSelected +=
new SilverlightColorPicker.ColorPicker.ColorSelectedHandler(colorPicker1_ColorSelected); } void colorPicker1_ColorSelected(Color c) { frame.Fill = new SolidColorBrush(c); pop.IsOpen = false; } private void frame_MouseRightButtonDown(object sender, MouseButtonEventArgs e) { e.Handled = true; } private void frame_MouseRightButtonUp(object sender, MouseButtonEventArgs e) { pop.HorizontalOffset = e.GetPosition(null).X + 2; pop.VerticalOffset = e.GetPosition(null).Y + 2; pop.IsOpen = true; }


Download source code

(requires Silverlight 4 beta)



Technorati Tags: