Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF MouseLeftButtonUp Not Firing

When I use the MouseUp event, I can get it to fire with a mouse right-click. But MouseLeftButtonUp won't fire with either click!

<Button MouseLeftButtonUp="btnNewConfig_MouseUp"  Name="btnNewConfig">
    <StackPanel Orientation="Horizontal">
        <Image Source="Icons\new.ico" Height="24" Width="24" Margin="5"/>
        <TextBlock VerticalAlignment="Center">New</TextBlock>
    </StackPanel>
</Button>

I know this is most likely something simple. Thanks for the help!

like image 625
Adam Driscoll Avatar asked Nov 25 '08 17:11

Adam Driscoll


3 Answers

Looks like Button control is eating up that event Since Button.Click is actually a combination of LeftButtonDown event and LeftButtonUp event.

But you can subscribe to the tunneled event PreviewMouseLeftButtonUp on the Button instead of LeftButtonUp.

like image 90
Jobi Joy Avatar answered Nov 16 '22 11:11

Jobi Joy


Subscribing to a tunneled event instead of a bubble one has some pretty messy side effects which I will explain later.

Here is a better solution as in it keeps your bubble intact. :)

btnNewConfig.AddHandler(MouseLeftButtonUpEvent, 
                        new RoutedEventHandler(btnNewConfig_MouseUp), 
                        true);

You will have to declare your event handler with RoutedEventArgs instead of MouseButtonEventArgs but you can just cast it back to MouseButtonEventArgs inside.

void btnNewConfig_MouseUp(object sender, RoutedEventArgs e)
{
    MouseButtonEventArgs args = e as MouseButtonEventArgs;
    // ...
}

Note the last argument in AddHandler - making it true causes your event to fire even if previous handler set e.Handled = true;

Now about PreviewMouseLeftButtonUp:

Tunneling events fire for parents before children. Bubbling - the opposite. If you have many event handlers involved you should really stick to all bubbling or all tunneling or else the more event handlers you add the more confusing it gets - adding one new event handler may cause you to revisit all the other ones in the application.

Most people find bubbling model a much more natural one. This is why the accepted answer is problematic.

like image 24
ILIA BROUDNO Avatar answered Nov 16 '22 10:11

ILIA BROUDNO


Button is using the Mouse[Left/Right]Button[Up/Down] events (and marking them as Handled) for its Button.Click events.

As Jobi said, you can use the PreviewMouseLeftButtonUp event, but I want to suggest that you create your own button template and modify its behavior. (i.e. not mark the MouseLeftButtonUp as Handled = true) or simply use something else than a Button as your parent container (depends on what you really need it for).

like image 4
matfillion Avatar answered Nov 16 '22 12:11

matfillion