The proposed solution above does not work (or did not work for me anyway) as you need to test for DataGridRow as well, otherwise you always get null if you are actually right-clicking on a valid row. Here is what worked correctly for me:
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;
}
}