ObjectiveThis article will give an introduction of mouse right click events on Silver Light controls. Silver Light 4.0 introduces context menu for all the controls.Right Click Mouse Event is added newly added feature in Silver Light 4.0. DesignCreate a Button on silver light page. <Grid x:Name="LayoutRoot" Background="Black"><Button x:Name="myButton" Width="75" Height="40" Background="Red" Content="Click Here" />
</Grid> Adding Right click eventsNow add mouse right click events to button. Context menu or Right click event could be added to any control in Silver Light 4.0
There are two Mouse right click events.
1. MouseRightButtonDown 2. MouseRightButtonUp So after adding the events myButton.MouseRightButtonDown += new MouseButtonEventHandler(mosuedown)
myButton .MouseRightButtonUp +=new MouseButtonEventHandler(mouseup); We could handle the event according to our need. void mouseup(object sender, MouseButtonEventArgs e)
{// Handle the event as of need }
void mosuedown(object sender, MouseButtonEventArgs e)
{// Handle the event as of need}While running above code, we will get below output. Once right click on button, default context of silver light will come. See the images below. On clicking on Silver Light, Silver Light configuration window will get open. See the image below. Disabling default context of Silver LightWe need to tell Silver Light that context has been handled by making handled as True. void mosuedown(object sender, MouseButtonEventArgs e)
{
e.Handled = true;
}After enabling handled true the default context of Silver Light will be disabled. Now if you run the application, you won’t get default silver light context on right click. Now, adding a message box to handle the events. Complete code is as below using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace TestingRightClickEvents
{public partial class MainPage : UserControl
{public MainPage()
{
InitializeComponent();
myButton.MouseRightButtonDown += new MouseButtonEventHandler(mosuedown);
myButton .MouseRightButtonUp +=new MouseButtonEventHandler(mouseup);
}void mouseup(object sender, MouseButtonEventArgs e)
{
MessageBox.Show("Right Click of Button is Up ");
}void mosuedown(object sender, MouseButtonEventArgs e)
{
e.Handled = true;
}
}
}Sample Output ConclusionIn this article, I introduced Context menu or Mouse Right click event handling in Silver Light 4.0 Thanks for reading. |