测试指针是否在 UIElement 上 [英] Test whether the pointer is over a UIElement

查看:23
本文介绍了测试指针是否在 UIElement 上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 WPF 中,我可以轻松测试鼠标是否位于 UIElement 上:

In WPF I can easily test whether the mouse is over a UIElement:

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

我想在 WinRT 中做同样的事情,但对于 Windows.UI.Xaml.UIElement,似乎没有与 IsMouseOver 等效的东西.

I want to do the same in WinRT, but there seems to be no equivalent to IsMouseOver for a Windows.UI.Xaml.UIElement.

Windows.UI.Xaml.UIElement el = ...;
bool isPointerOver = ???

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

As a workaround, I can add two handlers, for the PointerEntered and PointerExited events, but I'm looking for a more direct solution.

推荐答案

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

In uwp the UIElement doesn't have a property named IsPointerOver. But it has event handles of PointerEntered and PointExited as you known. We can custom the elements and define the new propertyIsPointerOver and wrapper these events. For example, I wrapper a custom control with the IsPointerOver property like follows:

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 元素.

More details please reference this thread. But this is not suit for all UI elements.

因此,您可以通过另一种方式调用 VisualTreeHelper.FindElementsInHostCoordinates 方法可以确定给定名称的元素是否存在于应用程序 UI 中某个点的 z 顺序中的任何位置.您可以获取鼠标指针的坐标并调用此方法来判断元素是否已指向.如何获取鼠标指针位置请参考BasicInput 官方示例.

So for another way you can invoke the 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 official sample.

这篇关于测试指针是否在 UIElement 上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆