Silverlight Datagrid right click

Is there a way for a right click event to select a row in a datagrid toolkit?

I use the toolkit context menu, which works great, but the problem is that only left-clicking allows me to select rows, and I need to right-click to be able to do this if I want my context menu to work correctly.

Any help is appreciated

+6
c # silverlight datagrid contextmenu
source share
5 answers

You can find the solution here .

It basically looks like this:

private void dg_LoadingRow(object sender, DataGridRowEventArgs e) { e.Row.MouseRightButtonDown += new MouseButtonEventHandler(Row_MouseRightButtonDown); } void Row_MouseRightButtonDown(object sender, MouseButtonEventArgs e) { dg.SelectedItem = ((sender) as DataGridRow).DataContext; } 
+5
source share

He is the behavior that will do the trick for you (inspired by this post):

 public class SelectRowOnRightClickBehavior : Behavior<DataGrid> { protected override void OnAttached() { base.OnAttached(); AssociatedObject.MouseRightButtonDown += HandleRightButtonClick; } protected override void OnDetaching() { base.OnDetaching(); AssociatedObject.MouseRightButtonDown += HandleRightButtonClick; } private void HandleRightButtonClick(object sender, MouseButtonEventArgs e) { var elementsUnderMouse = VisualTreeHelper.FindElementsInHostCoordinates(e.GetPosition(null), AssociatedObject); var row = elementsUnderMouse .OfType<DataGridRow>() .FirstOrDefault(); if (row != null) AssociatedObject.SelectedItem = row.DataContext; } } 

Use it as follows:

 <sdk:DataGrid x:Name="DataGrid" Grid.Row="4" IsReadOnly="True" ItemsSource="{Binding MyItems}"> <i:Interaction.Behaviors> <b:SelectRowOnRightClickBehavior/> </i:Interaction.Behaviors> </sdk:DataGrid> 
+3
source share

Thanks, good idea. But it was noted that with the UnloadingRow event it was more efficient.

 private void dg_UnloadingRow(object sender, System.Windows.Controls.DataGridRowEventArgs e) { e.Row.MouseRightButtonDown -= Row_MouseRightButtonDown; } 
+1
source share

This open source Codeplex project supports this behavior out of the box and does much more than this:

http://sl4popupmenu.codeplex.com/

+1
source share

I tried a slightly different approach using the LoadRow event in a DataGrid. I do not like to use this particular event if I do not need it, but since I did not work with large amounts of data, it works very well. The only thing I don’t have in this example is the command that I need to use to complete the action. You can use the command in a DataContext object or some other mechanism.

  private void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e) { var contextMenu = new ContextMenu(); var deleteMenuItem = new MenuItem {Header = "Delete User"}; contextMenu.Items.Add(deleteMenuItem); ContextMenuService.SetContextMenu(e.Row, contextMenu); } 
0
source share

All Articles