从列标题XAML中删除右键单击上下文菜单

从列标题XAML中删除右键单击上下文菜单

本文介绍了从列标题XAML中删除右键单击上下文菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的程序中,我有一个绑定到可观察列表的数据网格。我希望能够将上下文菜单设置为仅在选择行时显示,以便在没有选择任何内容时不会出现错误。为此,我希望能够禁用列标题上的上下文菜单。这是XAML:



In my program I have a datagrid which is bound to an observable list. I want to be able to set the context menu to only display when a row is selected so that there wont be errors with nothing being selected. To do this I would like to be able to disable the context menu on the column headers. Here is the XAML:

<DataGrid Name="dgItems" AutoGenerateColumns="False" SelectionMode="Single" SelectionUnit="FullRow" CanUserAddRows="False" IsReadOnly="True">
  <DataGrid.ContextMenu>
      <ContextMenu>
          <MenuItem Header="Edit Item" Click="EditItem_Click"/>
          <MenuItem Header="Delete Item" Click="DeleteItem_Click"/>
      </ContextMenu>
  </DataGrid.ContextMenu>
   <DataGrid.Columns>
      <DataGridTextColumn Header="Caption" Binding="{Binding Caption}"/>
      <DataGridTextColumn Header="Details" Binding="{Binding Details}"/>
      <DataGridTextColumn Header="DateFrom" Binding="{Binding DateFrom}"/>
      <DataGridTextColumn Header="DateTo" Binding="{Binding DateTo}"/>
      <DataGridTextColumn Header="Source" Binding="{Binding Source}"/>
   </DataGrid.Columns>
</DataGrid>



如何禁用标题上的上下文菜单?谢谢。


How would I go about disabling the context menus on the headers? Thanks.

推荐答案

private void DataGrid_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
    DependencyObject DepObject = (DependencyObject)e.OriginalSource;

    while ((DepObject != null) && !(DepObject is DataGridColumnHeader))
    {
        DepObject = VisualTreeHelper.GetParent(DepObject);
    }

    if (DepObject == null)
    {
        return;
    }

    if (DepObject is DataGridColumnHeader)
    {
          dgItems.ContextMenu.Visibility = Visibility.Collapsed;
    }
    else
    {
          dgItems.ContextMenu.Visibility = Visibility.Visible;
    }
}


        private void dgMP_MOCParts_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            DependencyObject DepObject = (DependencyObject)e.OriginalSource;

            while ((DepObject != null) && !(DepObject is DataGridColumnHeader)
&& !(DepObject is DataGridRow))
            {
                DepObject = VisualTreeHelper.GetParent(DepObject);
            }

            if (DepObject == null)
            {
                return;
            }

            if (DepObject is DataGridColumnHeader)
            {
                dgMP_MOCParts.ContextMenu.Visibility = Visibility.Collapsed;
            }
            else
            {
                dgMP_MOCParts.ContextMenu.Visibility = Visibility.Visible;
            }
        }


这篇关于从列标题XAML中删除右键单击上下文菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 19:00