如何在UWP或C#中找到指针输入指针或指针存在的指针事件类型?

时间:2017-12-11 13:42:07

标签: c# uwp uwp-xaml c++-cx

我们如何从RoutedEventArgs找到哪个指针事件类型? 就像我有一个HyperlinkButton和普通Button一样。 我希望在两个元素上使用鼠标PointerEntered / PointerExited时使用相同的方法。

HyperlinkButton hLinkBtn1 = new HyperlinkButton();
Button btn1 = new Button();
hLinkBtn1.PointerEntered += myEvent;
hLinkBtn1.PointerExited += myEvent;
btn1.PointerEntered += myEvent;
btn1.PointerExited += myEvent;

private void myEvent(object sender, PointerRoutedEventArgs e)
{
    // TODO
    // get pointer entered OR exited
}

1 个答案:

答案 0 :(得分:1)

使用as运算符转换sender参数:

private void myEvent(object sender, PointerRoutedEventArgs e)
{
    Button btn = sender as Button;
    if (btn != null)
    {
        //button was clicked...
    }
    else
    {
        HyperlinkButton hpl = sender as HyperlinkButton;
        if (hpl != null)
        {
            //hyperlink was clicked...
        }
    }
}
  

我的问题不是关于Element,我想知道触发了哪个事件。鼠标悬停/退出时,获取pointerEntered / pointerExited

您可以使用匿名事件处理程序调用接受参数的方法,该参数可用于判断是否引发了PointerEnteredPointerExited事件:

btn1.PointerEntered  += (ss, ee) => myEventHandler(ee, "PointerEntered");
btn1.PointerExited  += (ss, ee) => myEventHandler(ee, "PointerExited");
...

private void myEventHandler(PointerRoutedEventArgs ee, string eventType)
{
    switch(eventType)
    {
        case "PointerEntered":
            //...
        break;
        case "PointerExited":
       //...
        break;
}