How to know what control the mouse has clicked in a canvas?

别说谁变了你拦得住时间么 提交于 2019-12-25 16:02:30

问题


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.

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.

Thank you very much for you help


回答1:


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

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



来源:https://stackoverflow.com/questions/7011827/how-to-know-what-control-the-mouse-has-clicked-in-a-canvas

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