Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the clicked object from a MouseLeftButtonUp event registered on a parent container?

I have ellipses drawn on top of a canvas, I've registered a MouseLeftButtonUp on the Canvas, and I and want to get what ellipse was clicked using:

(Ellipse)e.Source

But e.Source is always the canvas, I also tried e.OriginalSource and also did the same thing with PreviewMouseLeftButtonUp, but still same result. Event arg is MouseButtonEventArgs. What am I doing wrong? also is there a way to check if there is a child element of a canvas at a specific point.

like image 446
mihajlv Avatar asked Oct 20 '25 14:10

mihajlv


2 Answers

Use e.OriginalSource instead.

like image 188
H.B. Avatar answered Oct 23 '25 07:10

H.B.


I just ran into this issue and this was the first answer to pop up. It was working for me on MouseLeftButtonDown but not on MouseLeftButtonUp. This was because of a logic error I had made with capturing the mouse in my MouseDown handler.

MouseUp events only fire on the element that is captured if you are capturing the element.

I had the following line in my MouseLeftButtonDown handler:

((FrameworkElement) sender).CaptureMouse();

Changing that to the following fixed the problem:

((FrameworkElement) e.OriginalSource).CaptureMouse();
like image 39
JVal90 Avatar answered Oct 23 '25 08:10

JVal90



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!