WPF ComboBox dropdown is preventing clicking other controls

你说的曾经没有我的故事 提交于 2020-01-24 20:16:15

问题


I have a simple form like this:

I open the combobox and at the time dropdown is open, I click the button. On button click I show a simple message but the message is not shown at that time. It shows when I click it again.

The same problem for textbox. When the dropdown is open, the textbox click is not working.

Why does combobox prevent clicking other controls when it is open?


回答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));
}

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

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;
}



回答2:


The combobox is implemented the way that it captures the mouse when the dropdown is open. This is done to easyly figure out when the user clicks outside of the combobox (in fact it's a one-liner). When the user clicks outside of the combobox it releases the mouse, closes the dropdown and marks the click as handled. The last action of course stops further processing and the click is not passed to the control you thought you clicked on.

My personal opinion is this behavior has pros and cons. Microsoft decided the way it is.



来源:https://stackoverflow.com/questions/40068021/wpf-combobox-dropdown-is-preventing-clicking-other-controls

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