WPF ComboBox: click outside of popup suppress mouse click

江枫思渺然 提交于 2019-12-02 01:41:08

问题


I use a standard WPF ComboBox control. When popup is opened and user clicks somewhere outside, popup is closed. But if there is button on the window and user clicks on it (with popup still opened), button's click handler is not executed. Popup is closed, but user has to click one more time on the button to raise click event on it.

I know that is standard behavior for this control. Have you any ideas how to bypass this behavior? Thanks!


回答1:


You can create an event for ComboBox DropDownClosed and with the hittestfunction, find the other control that the user has clicked.

private void ComboBox_DropDownClosed(object sender, EventArgs e)
{
    Point m = Mouse.GetPosition(this);
    VisualTreeHelper.HitTest(this, this.FilterCallback, this.ResultCallback, new PointHitTestParameters(m));
}

private HitTestFilterBehavior FilterCallback(DependencyObject o)
{
    var c = o as Control;
    if ((c != null) && !(o is MainWindow))
    {
        if (c.Focusable)
        {
            if (c is ComboBox)
            {
                (c as ComboBox).IsDropDownOpen = true;
            }
            else
            {
                var mouseDevice = Mouse.PrimaryDevice;
                var mouseButtonEventArgs = new MouseButtonEventArgs(mouseDevice, 0, MouseButton.Left)
                {
                    RoutedEvent = Mouse.MouseDownEvent,
                    Source = c
                };
                c.RaiseEvent(mouseButtonEventArgs);
            }

            return HitTestFilterBehavior.Stop;
        }
    }
    return HitTestFilterBehavior.Continue;
}

private HitTestResultBehavior ResultCallback(HitTestResult r)
{
    return HitTestResultBehavior.Continue;
}

Then in the FilterCallback function after finding that control, raise the mouse down event on that control.

I found the raise event, does not work on comboboxes so for clicking that, I simply set the IsDropDownOpen to true.

I found the code in here and modified it a little.




回答2:


You can try to release the mouse capture right after the ComboBox gets one: In your's ComboBox properties in XAML:

GotMouseCapture="ComboBox_OnGotMouseCapture"

And in code-behind:

private void ComboBox_OnGotMouseCapture(object sender, MouseEventArgs e)
{
    ComboBox.ReleaseMouseCapture();
}


来源:https://stackoverflow.com/questions/37891680/wpf-combobox-click-outside-of-popup-suppress-mouse-click

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