Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing parent event fired when there's also Child control event fired

Tags:

c#

mouseevent

wpf

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.

like image 328
Moses Aprico Avatar asked Dec 15 '22 22:12

Moses Aprico


1 Answers

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
   }

}
like image 161
dkozl Avatar answered May 21 '23 16:05

dkozl