我们如何从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
}
答案 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
您可以使用匿名事件处理程序调用接受参数的方法,该参数可用于判断是否引发了PointerEntered
或PointerExited
事件:
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;
}