Why doesn't button click event “bubble up visual tree” to StackPanel as MSDN article states?

前端 未结 5 1704
鱼传尺愫
鱼传尺愫 2021-02-12 09:49

In the MSDN article Understanding Routed Events and Commands In WPF, it states

an event will bubble (propagate) up the visual tree from the source ele

5条回答
  •  名媛妹妹
    2021-02-12 10:24

    As others have said, it's because the MouseDown event gets handled by the Button before it can be bubbled further. You can see this in Reflector, in ButtonBase.OnMouseLeftButtonDown:

    protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
    {
        if (this.ClickMode != ClickMode.Hover)
        {
            e.Handled = true;
            // SNIP...
        }
        base.OnMouseLeftButtonDown(e);
    }
    

    One solution is to listen for a MouseDown event, and indicate that you don't care if the event is handled. You can do this with the AddHandler method. It has a boolean overload that lets you listen for events which are already handled.

    If you do this somewhere instead of setting the MouseDown handler in XAML:

    TheStackPanel.AddHandler(MouseDownEvent, new MouseButtonEventHandler(TheStackPanel_MouseDown), true);
    

    You'll receive all MouseDown events on TheStackPanel, regardless of whether they've been handled.

提交回复
热议问题