3
votes

I have a DataGrid created in XAML in a C# project. I've added a context menu to the rows. Basically when the user clicks directly on the cell it should open the relevant item in the current window, which is implemented on the SelectionChanged event.

However if the user right clicks a row it should show the the context menu without selecting the row, so that the user can select an item in the context menu to open the relevant item in a new window. So they can look at both the already selected item and the new item at once, but as the right click selects the row, the user see the newly selected item in the current window and the new window.

How can I stop the right click action to show the context menu from selecting the cell?

1

1 Answers

0
votes

For my solution, I have to overwrite the following two event handlers (i.e., PreviewMouseRightButtonDown and PreviewMouseRightButtonUp). Plus, not sure why data-binding for the ItemsSource does not work, so that I have to bind it manually.

    private void ResultDataGrid_PreviewMouseRightButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        if (sender is DataGrid dg)
        {
            if (this.DataContext is PipelineStepResultViewModel dataContext
                && dataContext.DatagridMenuItems != null)
            {
                dg.ContextMenu.ItemsSource = dataContext.DatagridMenuItems;
            }
        }

        e.Handled = true;
    }

    private void ResultDataGrid_PreviewMouseRightButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        if (sender is DataGrid dg && dg.ContextMenu.ItemsSource != null)
        {
            ResultDataGrid.ContextMenu.IsOpen = true;
        }
        e.Handled = true;
    }