views:

386

answers:

3

I have the following XAML code:

<Grid Background="Blue">
        <Grid MouseLeftButtonDown="Grid_MouseLeftButtonDown">
            <CheckBox MouseLeftButtonDown="CheckBox_MouseLeftButtonDown_1"></CheckBox>
        </Grid>
</Grid>

When i click the checkbox with the mouse left button, the declared event is not fired. Can anyone have an explanation for this behaviour? Thanks in advance

+3  A: 

The event is being handled by something else (probably being consumed by the Checked event).

If you change the event to PreviewMouseLeftButtonDown (the tunneling version of MouseLeftButtonDown), it will fire properly.

Charlie
+1  A: 

The CheckBox inherits from ButtonBase, which add a class handler for the left button down event (OnMouseLeftButtonDown). As the documentation for UIElement.MouseLeftButtonDown event mentions (emphasis mine):

Some control classes might have inherent class handling for mouse button events. The left mouse button down event is the most likely event to have class handling in a control. The class handling often marks the underlying Mouse class event as handled. Once the event is marked handled, other instance handlers that are attached to that element are not ordinarily raised. Any other class or instance handlers that are attached to elements in the bubbling direction towards the root in the UI tree are also not ordinarily raised.

You can play with the ClickMode and set it to ClickMode.Hover, which seems to prevent the behavior you are seeing. However, you might have to then maintain a custom logic in your event handler for this particular instance to set the proper toggle state of your check box.

You can also try the PreviewMouseLeftButtonDown event. However, marking that event as handled in your handler might have side effects on the rest of the MouseDown events - they will carry the handled information, which will prevent other instance handlers unless they are added with AddHandler with the flag for handling already handled events.

Franci Penov
Take my idea without up-voting my answer? Brutal there, Franci.
Charlie
Lol, @Charlie, you don't own the PreviewMouseLeftButtonDown event. It's a public event. :-) But you did mention it before me, so I gave you your upvote (unfortunately, you can get only one from me, though).
Franci Penov
Haha that is correct and it is no big deal. But you did edit your post to include it after reading mine. :)
Charlie
A: 

Franci thanks for your reply...I need to checkbox MouseLeftDownEvent to fire, and setting clickMode = hover solved my problem. I need MouseleftDownEvent to bubble the event to the parent grid.

JP