C# WPF 如何检查鼠标是否在 DataGridComboBoxColumn 上

C# WPF How to check if mouse is over DataGridComboBoxColumn

我正在尝试在数据网格行上使用拖放功能,并且我在数据网格列上使用了 MouseMove 事件处理程序。但是现在我不能再点击组合框了。我正在考虑执行检查以查看鼠标是否位于组合框列上,如果是则退出该功能。但我不知道该怎么做。发件人只是 DataGrid 类型,我无法使用它。任何帮助将不胜感激。

您可以通过 MouseMovePreviewMouseMove 事件确定列的基础类型:

private void DataGrid_OnPreviewMouseMove(object sender, MouseEventArgs e)
{
    var dataGrid = (DataGrid)sender;

    var inputElement = dataGrid.InputHitTest(e.GetPosition(dataGrid)); // Get the element under mouse pointer

    var cell = ((Visual)inputElement).GetAncestorOfType<DataGridCell>(); // Get the parent DataGridCell element

    if (cell == null)
        return; // Only interested in cells

    var column = cell.Column; // Simple...

    if (column is DataGridComboBoxColumn comboColumn)
        ; // This is a combo box column
}

您会注意到我在这里使用了一个有趣的扩展。这是来源:

/// <summary>
/// Returns a first ancestor of the provided type.
/// </summary>
public static Visual GetAncestorOfType(this Visual element, Type type)
{
    if (element == null)
        return null;

    if (type == null)
        throw new ArgumentException(nameof(type));

    (element as FrameworkElement)?.ApplyTemplate();

    if (!(VisualTreeHelper.GetParent(element) is Visual parent))
        return null;

    return type.IsInstanceOfType(parent) ? parent : GetAncestorOfType(parent, type);
}

/// <summary>
/// Returns a first ancestor of the provided type.
/// </summary>
public static T GetAncestorOfType<T>(this Visual element)
    where T : Visual => GetAncestorOfType(element, typeof(T)) as T;

这是从可视化树中获取 parent/ancestor 元素的众多方法之一,我一直使用它来完成您面临的任务。

您会发现 InputHitTest 方法和上述扩展是您 Drag/Drop 例程中的宝贵资产。