0

I have this kind of problem. I normally select row in datagrid by left or right mouse click. But I need on right click run command. I use this code

<DataGrid.InputBindings> <MouseBinding Command="{Binding ShowDWClickOnRightButton}" MouseAction="RightClick" CommandParameter="{Binding ElementName=myDataGrid, Path=SelectedItem}"/> </DataGrid.InputBindings>

But this not working, because in command parameter I have null (no selected Item). Can you please give me some advice how to solve this?

Thank you

MarekJ
  • 53
  • 4
  • I have written a behavior, which select item on right click. It is for a TreeView, but I think you can adjust it for a GridView. Take a look: https://stackoverflow.com/a/43118460/7713750 – Rekshino Jul 25 '17 at 06:29
  • I try check you solution ... i need select and run command with selected row. So hope it will be possible. – MarekJ Jul 25 '17 at 19:38

1 Answers1

0

You cannot use SelectedItem because it is not set when right mouse button is clicked.

  1. You can either set selectedItem before right mouse button is pressed

  2. Call some method from your ViewModel directly from codebehind with appropriate row object: wpf:

    < DataGrid Grid.Row="1" x:Name="myDataGrid" MouseRightButtonDown="myDataGrid_MouseRightButtonDown" ...

codebehind:

private void myDataGrid_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.OriginalSource == null) return;
            var row = ItemsControl.ContainerFromElement((DataGrid)sender, e.OriginalSource as DependencyObject) as DataGridRow;

            if (row != null)
            {
                (this.DataContext as ViewModel).SomeViewModelMethod(row.DataContext as YourRowClass);
            }
        }
  1. Set Command in ItemTemplate like in this answer
lukbl
  • 1,763
  • 1
  • 9
  • 13