如何知道鼠标在画布中单击了什么控件?
我正在创建一个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.