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

本文关键字:单击 上下文 菜单 右键 删除 标题 | 更新日期: 2023-09-27 18:16:38

在我的程序中,我有一个绑定到一个可观察列表的数据网格。我希望能够将上下文菜单设置为仅显示时,一行被选中,这样就不会有错误与没有被选中。要做到这一点,我希望能够禁用列标题上的上下文菜单。下面是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>

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

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

可以使用DataTrigger设置ContextMenu。触发器监听SelectedItems.IsEmpty,如果监听false,则设置ContextMenu:

<DataGrid ... >
   <DataGrid.Resources>
       <ContextMenu x:Key="cm">
            <MenuItem Header="Edit Item" Click="EditItem_Click"/>
            <MenuItem Header="Delete Item" Click="DeleteItem_Click"/>
       </ContextMenu>
   </DataGrid.Resources>
   <DataGrid.Style>
      <Style TargetType="DataGrid">
         <Style.Triggers>
             <DataTrigger Binding="{Binding SelectedItems.IsEmpty, 
                          RelativeSource={RelativeSource Self}}" Value="false">
                 <Setter Property="ContextMenu" Value="{StaticResource cm}"/>
             </DataTrigger>
         </Style.Triggers>
      </Style>
   </DataGrid.Style>
   <!-- remaining code -->
</DataGrid>

您可以尝试拦截事件并将其标记为已处理。首先在网格上添加事件:

<DataGrid
ItemsSource="{Binding ClassroomStudents, Mode=TwoWay}"
MouseRightButtonUp="DataGrid_MouseRightButtonUp"
</DataGrid>

然后标记为已处理:

private void DataGrid_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
{
    DependencyObject depObj = e.OriginalSource as DependencyObject;
    while(depObj != null && !(depObj is DataGridColumnHeader))
    {
        depObj = VisualTreeHelper.GetParent(depObj);
    }
    if(depObj is DataGridColumnHeader)
    {
        e.Handled = true;
    }
}