简体   繁体   English

在 DataGrid 中右键单击选择

[英]Right click selection in DataGrid

I have a DataGrid created in XAML in a C# project.我在 C# 项目中使用 XAML 创建了一个 DataGrid。 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.基本上,当用户直接单击单元格时,它应该在当前窗口中打开相关项目,这是在SelectionChanged事件上实现的。

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?如何停止右键单击操作以显示选择单元格的上下文菜单?

See wpf listview right-click problem for a potential answer; 有关潜在答案,请参阅wpf listview右键单击问题 ; not much more to say... the Preview events should help. 没什么可说的......预览活动应该有所帮助。

For my solution, I have to overwrite the following two event handlers (ie, PreviewMouseRightButtonDown and PreviewMouseRightButtonUp).对于我的解决方案,我必须覆盖以下两个事件处理程序(即 PreviewMouseRightButtonDown 和 PreviewMouseRightButtonUp)。 Plus, not sure why data-binding for the ItemsSource does not work, so that I have to bind it manually.另外,不确定为什么 ItemsSource 的数据绑定不起作用,所以我必须手动绑定它。

    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;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM