如何知道鼠标在画布中单击了什么控件? [英] How to know what control the mouse has clicked in a canvas?

查看:63
本文介绍了如何知道鼠标在画布中单击了什么控件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个C#WPF应用程序,并正在寻找一种执行以下操作的方法:

I am creating a C# WPF application and looking for a way to do the following:

我有一个包含不同用户控件的画布和一个按钮.

I have a canvas with different user controls in it and a button.

当我单击按钮时,光标变为手形(Canvas.Cursor = Cursors.Hand)

When I click on the button the cursor change to a hand (Canvas.Cursor = Cursors.Hand)

然后,如果我单击其中一个控件,则会显示一个消息框,显示单击的控件的名称(名称是控件的公共属性).

Then if I click on one of the controls I get a message box showing the name of the control clicked (the name is a public property of the control).

如果我单击其他位置,则光标会重置,应该再次单击该按钮,然后才能再次获得名称.

If I click somewhere else i the cursor resets and I should click on the button again before I can get the name again.

我尝试使用事件和处理程序,但无法实现我想要的.

I tried playing with events and handlers but couldn't achieve what I wanted.

非常感谢您的帮助

推荐答案

您可以使用Canvas.MouseDown并将VisualTreeHelper.HitTest()与鼠标按下事件args的GetPosition()结合使用,以获取被单击的元素.

You can use Canvas.MouseDown and use VisualTreeHelper.HitTest() with GetPosition() of the mouse down event args to get the element that was clicked.

<Canvas Name="myCanvas" MouseDown="MouseDownHandler" />

public void MouseDownHandler(object sender, MouseButtonEventArgs e)
{
    HitTestResult target = VisualTreeHelper.HitTest(myCanvas, e.GetPosition(myCanvas));

    while(!(target is Control) && (target != null))
    {
        target = VisualTreeHelper.GetParent(target);
    }
    // now if target is not null, it's the control that was clicked...
}

然后,您可以使用VisualTreeHelper.GetParent()(在while循环中)获取被单击的控件.

Then you can use VisualTreeHelper.GetParent() (in a while loop) to get the control that was clicked.

这篇关于如何知道鼠标在画布中单击了什么控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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