WPF MouseLeftButtonUp Not Firing

萝らか妹 提交于 2019-11-27 16:02:58

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 Tunnelled event PreviewMouseLeftButtonUp on the Button to get LeftButtonUp

Button is using the MouseLeft/RightButtonUp/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).

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!