0
votes

In Silverlight 5, I have a DataGrid with a ContextMenuService.ContextMenu. If you click a row to select, then right click, you just check the grid.selecteditem for context. However, if you right click a row without selecting it, you don't have that row's context when the menu opens. How do you get the DataContext row of the grid that was right clicked on when the context menu opens? The right click on the grid seems to be an option, but it is intercepted for the contextmenu and does not fire unless a contextmenu is already open/in focus.

I have found tons of examples of getting around the original issue with Silverlight 4 and detecting the rown on right click. However, the contextmenu now intercepts the rigth click of the grid, so those no logner work. I also found posts on 'bugs' with the initial relase of the ContextMenu. All these posts/blogs are making it hard to find a current answer or solution.

2
... no work around yet. For now, if the grid.selectedItem is null, I prompt the user to select a row. Also, after the context menu does it's work, I deselect the current grid.selected item.Roger

2 Answers

1
votes

yeah it seems like Silverlight 5 has changed something that breaks the old tricks.

We've been doing this: add row enters on row load handler. EG:

private void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
{
        e.Row.MouseEnter += new MouseEventHandler(Row_MouseEnter);
        e.Row.MouseLeave += new MouseEventHandler(Row_MouseLeave);
}


void Row_MouseEnter(object sender, MouseEventArgs e)
{
        DataGridRow dgr = sender as DataGridRow;
        IncidentGrid.SelectedItem = dgr.DataContext;
}

pretty ugly i know, but it's working.

0
votes

Besides Roger's concerns of accuracy, I didn't want to wire up those events on every row because my grid is quite large, and I have to keep it lean.

I found a solution here...

https://mutelight.org/silverlight-datagrid-make-right-click-select-a-row

Apply just one event handler to the grid's MouseRightButtonDown event. The event args has the mouse position and you can use VisualTreeHelper to find which DataGridRow the mouse is over. Then that row's DataContext will have your SelectedItem.