С# WPF Как проверить, находится ли мышь над DataGridComboBoxColumn

Я пытаюсь сделать функцию перетаскивания в строках сетки данных и использовал обработчик событий MouseMove в столбцах сетки данных. Но теперь я больше не могу нажимать на поле со списком. Я думал о выполнении проверки, чтобы увидеть, находится ли мышь над столбцом поля со списком, и выйти из функции, если это так. Но я не знаю, как это сделать. Отправитель имеет только тип DataGrid, и я не могу его использовать. Любая помощь приветствуется.


person M. Chris    schedule 27.06.2018    source источник


Ответы (1)


Вы можете определить базовый тип столбца с помощью событий MouseMove или PreviewMouseMove как таковых:

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;

Это один из многих подходов к получению родительского/предкового элемента из визуального дерева, я постоянно использую его для таких задач, как та, с которой вы столкнулись.

Вы обнаружите, что метод InputHitTest и вышеуказанное расширение являются бесценными активами в ваших процедурах перетаскивания.

person bokibeg    schedule 28.06.2018