SilverLight 4.0 introduced lot of new features for its users including the support for Context Menu. By default, if you right click on any SilverLight control, it shows the installed SilverLight version on your machine.

In this blog, I would explain the implementation to show a right click context menu in Spread for Silverlight and customize it to work with Spread.

To begin with, we need to get the latest Silverlight 4.0 update. Once the update is complete, follow the given steps to implement the context menu.

1. Start a new Silverlight project and add Spread control in the Silverlight page like this:


<Grid x:Name="LayoutRoot" Background="White">
<ss:GcSpreadSheet HorizontalAlignment="Left" Margin="51,43,0,0" Name="gcSpreadSheet1" VerticalAlignment="Top" />
</Grid>




2. Add following references to your project.

  • System.Windows.Controls

  • System.Windows.Controls.Input.Toolkit.


3. In the UserControl XAML, add the following event handler for GC Spreadsheet:


MouseRightButtonDown="gcSpreadSheet1_MouseRightButtonDown"




4. Using the above MouseRightButtonDown event, we can add context menu to the Spread control through code.


private void gcSpreadSheet1_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
e.Handled = true;

cmenu = new ContextMenu();
mItem = new MenuItem();
mItem.Header = "Number Cell";
cmenu.Items.Add(mItem);
mItem.Click += new RoutedEventHandler(mItem_Click);

mItem = new MenuItem();
mItem.Header = "Date Cell";
cmenu.Items.Add(mItem);
mItem.Click += new RoutedEventHandler(mItem_Click);

cmenu.IsOpen = true;
cmenu.HorizontalOffset = e.GetPosition(LayoutRoot).X;
cmenu.VerticalOffset = e.GetPosition(LayoutRoot).Y;
}


You may add as many items you want and write code to handle the action for them. Action handlers for the above menu items are implemented below.


void mItem_Click(object sender, RoutedEventArgs e)
{
// throw new NotImplementedException();
MenuItem menuItem = (MenuItem)sender;
GrapeCity.Windows.SpreadSheet.Data.CellRange r;

r = new GrapeCity.Windows.SpreadSheet.Data.CellRange(0, 0, 2, 2);
switch (menuItem.Header.ToString())
{
case "Number Cell":
gcSpreadSheet1.ActiveSheet.ActiveCell.Formatter = new GrapeCity.Windows.SpreadSheet.Data.GeneralFormatter(GrapeCity.Windows.SpreadSheet.Data.FormatMode.StandardNumericMode, "c");
break;
case "Date Cell":
gcSpreadSheet1.ActiveSheet.ActiveCell.Formatter = new GrapeCity.Windows.SpreadSheet.Data.GeneralFormatter(GrapeCity.Windows.SpreadSheet.Data.FormatMode.StandardDateTimeMode, "M");
break;
default:
break;
}

cmenu.IsOpen = false;
}




5. Build your project and run it in IE. Select a cell and do a right click on the Spread control, the context menu is shown with two options to set the format of a cell as Date or Number.

Refer to the attached samples for complete implementation. The attached samples perform more operations with right click menu like , Cut, Copy etc.
Download Sample C#
Download Sample VB