Question

I'm struggling with an issue that is driving me crazy.

Here is my XAML code (simplified) :

<UserControl>
   <Canvas>
      <Grid>
         <ScrollViewer>
            <StackPanel Orientation="Horizontal">
               <StackPanel Orientation="Vertical">
                  <Canvas>
                     <Button Name="theButton" Click="theButton_Click"></Button>
                     <ComboBox Name="theCombo" SelectionChanged="theCombo_SelectionChanged"></ComboBox>
                  </Canvas>
               </StackPanel>
            </StackPanel>
         </ScrollViewer>
      </Grid>
   </Canvas>
</UserControl>

In the constructor of that UserControl :

AddHandler(MouseLeftButtonDownEvent, new MouseButtonEventHandler(UserControl_MouseDown), true);

I need to capture mouse clicks for my own UserControl (I have to draw a selection rectangle with the mouse on top of it). So I use AddHandler(), and I indicate "true" so that I can hook the MouseLeftButtonDownEvent even if it has been handled by my Button "theButton" (because when a button is clicked, it marks the event Handled property as true as MSDN says)

When I click inside my UserControl, my function UserControl_MouseDown is normally called. But when I click on my Button, the associated handler("theButton_Click") is never called. Same thing for the SelectionChanged event of my ComboBox : its handler is never called.

I used a tool called Snoop to see the event routing, and it seems to be normal : my button catches the MouseDown, then sets to True its Handled property. But the code never reaches the handler.

If I unhook the event for my UserControl, it's OK. I tried with PreviewMouseDown for the Button. It runs, but I can't use this for my ComboBox

Do you have any clue to solve that issue and make my UserControl and my Button and ComboBox call their respective handlers ?

Thanks for your help

edit: code of my UserControl's event handler

private void UserControl_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left && !_isMoving)
            {
                _isLeftMouseButtonDownOnWindow = true;
                _origMouseDownPoint = e.GetPosition(this);
                this.CaptureMouse();
                e.Handled = true;
            }
        }
Was it helpful?

Solution

Problem solved after copy/paste of my handler's code... by removing this line :

this.CaptureMouse();

That was so obvious... My bad

OTHER TIPS

I don't know why it's Handled even though you set it with true for handled events

but you can just catch it before the button :

 AddHandler(PreviewMouseLeftButtonDownEvent, new MouseButtonEventHandler(UserControl_MouseDown), true);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top