测试指针是否在 UIElement 上

Test whether the pointer is over a UIElement

在 WPF 中我可以很容易地测试鼠标是否在 UIElement:

System.Windows.UIElement el = ...;
bool isMouseOver = el.IsMouseOver;

我想在 WinRT 中做同样的事情,但对于 Windows.UI.Xaml.UIElement

似乎没有等同于 IsMouseOver 的东西
Windows.UI.Xaml.UIElement el = ...;
bool isPointerOver = ???

作为解决方法,我可以为 PointerEntered 和 PointerExited 事件添加两个处理程序,但我正在寻找更直接的解决方案。

在 uwp 中,UIElement 没有名为 IsPointerOver 的 属性。但如您所知,它具有 PointerEnteredPointExited 的事件句柄。我们可以自定义元素并定义新的 属性IsPointerOver 并包装这些事件。例如,我用 IsPointerOver 属性 包装了一个自定义控件,如下所示:

class NewButton : Button
{
    public static readonly DependencyProperty IsPointOverProperty = DependencyProperty.Register(
        "IsPointerOver", typeof(bool), typeof(NewButton), new PropertyMetadata(false));

    public  bool IsPointOver
    {
        get { return (bool)GetValue(IsPointOverProperty); }
        set { SetValue(IsPointOverProperty, value); }
    }       
    protected override void OnPointerEntered(PointerRoutedEventArgs e)
    {
        base.OnPointerEntered(e);
        IsPointOver = true;
    }
    protected override void OnPointerExited(PointerRoutedEventArgs e)
    {
        base.OnPointerExited(e);
        IsPointOver = false;
    }       
}

更多详情请参考。但这并不适合所有 UI 元素。

因此,您可以通过另一种方式调用 VisualTreeHelper.FindElementsInHostCoordinates method which can determines whether an element of a given Name exists anywhere in the z-order at a Point in the UI of an app. You can get the coordinates of the mouse pointer and invoke this method to judge whether the element is point over. For how to get the mouse pointer location please reference the scenario 2 of the BasicInput 官方示例。

在 UWP 中,使用 PointerRoutedEventArgs.GetCurrentPoint(UIElement) 获取相对于指定元素左上角的指针位置。假设你的 UIElement 是矩形的,你可以测试这个点的 X 和 Y >= 0 和 < width / height。