答案 0 :(得分:1)
您应该向整个 DataGrid 声明 ContextMenu:
<DataGrid ContextMenu="{StaticResource ColumnChooserMenuDataGrid}"
PreviewMouseRightButtonUp="DataGrid_PreviewMouseRightButtonUp">
...
</DataGrid>
编写事件处理程序:
private void Grid_PreviewMouseRightButtonUp(object sender, MouseButtonEventArgs e)
{
if (VisualHelper.FindVisualParent<DataGridColumnHeader>((DependencyObject)e.OriginalSource) != null)
return;
if (VisualTreeHelper.HitTest((Visual)e.OriginalSource, e.GetPosition((UIElement)sender))?.VisualHit is DataGridHeaderBorder)
return;
e.Handled = true;
}
VisualHelper 在哪里:
public static class VisualHelper
{
public static T FindVisualParent<T>(DependencyObject d) where T : class
{
while (d != null && !(d is T))
d = VisualTreeHelper.GetParent(d);
return d as T;
}
}