【wpf】MouseLeftButtonDown

今天自定义控件的时候,重写OnMouseLeftButtonDown发现根本不会被触发

后改为OnPreviewMouseLeftButtonDown,就触发成功了!

原因不明,后续再看


翻到了WPF的源码。

dotnet/wpf: WPF is a .NET Core UI framework for building Windows desktop applications. (github.com)

protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
        {
            // Ignore when in hover-click mode.
            if (ClickMode != ClickMode.Hover)
            {
                e.Handled = true;

                // Always set focus on itself
                // In case ButtonBase is inside a nested focus scope we should restore the focus OnLostMouseCapture
                Focus();

                // It is possible that the mouse state could have changed during all of
                // the call-outs that have happened so far.
                if (e.ButtonState == MouseButtonState.Pressed)
                {
                    // Capture the mouse, and make sure we got it.
                    // WARNING: callout
                    CaptureMouse();
                    if (IsMouseCaptured)
                    {
                        // Though we have already checked this state, our call to CaptureMouse
                        // could also end up changing the state, so we check it again.
                        if (e.ButtonState == MouseButtonState.Pressed)
                        {
                            if (!IsPressed)
                            {
                                SetIsPressed(true);
                            }
                        }
                        else
                        {
                            // Release capture since we decided not to press the button.
                            ReleaseMouseCapture();
                        }
                    }
                }

                if (ClickMode == ClickMode.Press)
                {
                    bool exceptionThrown = true;
                    try
                    {
                        OnClick();
                        exceptionThrown = false;
                    }
                    finally
                    {
                        if (exceptionThrown)
                        {
                            // Cleanup the buttonbase state
                            SetIsPressed(false);
                            ReleaseMouseCapture();
                        }
                    }
                }
            }

            base.OnMouseLeftButtonDown(e);
        }

有的控件(比如Button)当你单击时,触发的是Click事件。

其实MouseLeftButtonDown是被触发了,对于Button这种控件而言这个事件触发了之后,它直接触发Click事件,并且e.Handled = true 这个消息就结束了。

PreviewMouseLeftButtonDown优先级别更高,在MouseLeftButtonDown之前就触发了。

posted @ 2021-11-08 13:39  宋桓公  阅读(94)  评论(0编辑  收藏  举报