I'm not quite sure how to entitle it, but, say I have 3 red Rectangle
on the center of a Canvas
.
If I click on a Rectangle
, the color changes to blue, and if I click within the Canvas
but not the Rectangle
, each of the blue Rectangle
switch color back to red.
My problem is this : If I make 2 MouseLeftButtonDown
event, each for the Rectangle
-s and another is for the Canvas
, then if I click on the Rectangle
, the Canvas_MouseLeftButtonDown
event also fired after the Rectangle
one.
Question : How to prevent Canvas_MouseLeftButtonDown
(Parent control) event fired if there's a Child control which also Clicked.
Thanks.
UPDATE +code :
This is the Rectangle
event :
private void rectangle_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
//Change clicked rectangle color to blue
}
This is the Canvas
event :
private void canvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
//Change all Child rectangle color back to red
}
What I want in 1 sentence : If the "rectangle" event fires, the "canvas" one is prevented to fire.
Since the in-method code is not quite relevant to the question, then I remove it to make it look simpler.
You can set Handled
to true in Rectangle.MouseLeftButtonDown
handler
private void rectangle_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
e.Handled = true;
}
from MSDN
Marking the event handled will limit the visibility of the routed event to listeners along the event route. The event does still travel the remainder of the route, but only handlers specifically added with HandledEventsToo true in the AddHandler(RoutedEvent, Delegate, Boolean) method call will be invoked in response
EDIT
As an alternative solution you can keep only Canvas.MouseLeftButtonDown
event handler and remove one for Rectangle
and then do something like this
private void canvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (e.OriginalSource is Rectangle)
{
var myRectangle = e.OriginalSource as Rectangle;
//your code for Rectangle clicked
}
else if (e.OriginalSource is Canvas)
{
var myCanvas = e.OriginalSource as Canvas;
//your code for Canvas clicked
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With