SL4: DataGrid and contextmenu

There is a nice implementation of contextmenu by Jesse Bishop in SL4. It supports commands as well as click handlers
we could use that control and add context sensitive contextmenu to datagrid

I created a basic application, Here is the xaml for the mainpage. we have a datagrid which is bound to a list of persons

<UserControl xmlns:my=”clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data”  x:Class=”SilverlightApplication1.MainPage”
    d:DesignHeight=”300″ d:DesignWidth=”400″>

    <Grid x:Name=”LayoutRoot” Background=”White”>
<my:DataGrid x:Name=”datagrid1″ ItemsSource=”{Binding Persons}”></my:DataGrid>

when the rightmouse button is down on the grid. we do a hit test to get the row( the person item that was clicked), create a menuitem with person’s name and add to the Items of the contextmenu
when the item is clicked we remove the person from the list

void datagrid1_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
IEnumerable elements = VisualTreeHelper.FindElementsInHostCoordinates(e.GetPosition(LayoutRoot), datagrid1);
DataGridRow row = null;
foreach (UIElement ele in elements)
if (ele is DataGridRow)
row = ele as DataGridRow;

ContextMenu cm = new ContextMenu();
Person p = row.DataContext as Person;
MenuItem mi = new MenuItem { Text = “Delete ” + p.FirstName, Tag=p };
mi.Click += new MenuItem.ClickHandler(mi_Click);

datagrid1.SetValue(ContextMenu.ContextMenuProperty, cm);
cm.IsOpen = true;


void mi_Click(object sender, EventArgs e)
Persons.Remove((sender as MenuItem).Tag as Person);

you can download the sample here