【问题标题】:Right click selection in DataGrid在DataGrid中右键选择
【发布时间】:2013-02-26 20:18:25
【问题描述】:

我在 C# 项目的 XAML 中创建了一个 DataGrid。我在行中添加了一个上下文菜单。基本上,当用户直接单击单元格时,它应该在当前窗口中打开相关项目,这是在SelectionChanged 事件上实现的。

但是,如果用户右键单击一行,它应该显示上下文菜单而不选择该行,以便用户可以在上下文菜单中选择一个项目以在新窗口中打开相关项目。因此他们可以同时查看已选择的项目和新项目,但是当右键单击选择行时,用户会在当前窗口和新窗口中看到新选择的项目。

如何停止右键单击操作以显示上下文菜单以选择单元格?

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    对于我的解决方案,我必须覆盖以下两个事件处理程序(即 PreviewMouseRightButtonDown 和 PreviewMouseRightButtonUp)。另外,不知道为什么 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;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-02
      • 1970-01-01
      • 1970-01-01
      • 2013-08-22
      • 1970-01-01
      • 2011-01-01
      • 2022-12-03
      相关资源
      最近更新 更多