0

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

Y2theZ
  • 10,162
  • 38
  • 131
  • 200
  • If you tried playing with events and handlers but couldn't achieve what you wanted then you probably didn't play long enough...can you show what you tried, maybe we can help you de-bug. – Chris Pfohl Aug 10 '11 at 13:48

1 Answers1

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.

Martin Hennings
  • 16,418
  • 9
  • 48
  • 68