Test whether the pointer is over a UIElement

删除回忆录丶 提交于 2021-01-27 21:20:22

问题


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

System.Windows.UIElement el = ...;
bool isMouseOver = el.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 = ???

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


回答1:


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;
    }       
}

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

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.




回答2:


In UWP, use PointerRoutedEventArgs.GetCurrentPoint( UIElement) to get the pointer location relative to the top left corner of the specified element. Assuming your UIElement is rectangular, you can just test that the X and Y of this point are >= 0 and < width / height.



来源:https://stackoverflow.com/questions/39694242/test-whether-the-pointer-is-over-a-uielement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!