Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF ComboBox: click outside of popup suppress mouse click

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!

like image 868
andrei.aliashkevich Avatar asked Oct 21 '25 06:10

andrei.aliashkevich


1 Answers

I fixed some bugs with @Eng. M.Hamdy very good approach and did it in C#, also applying it to all comboboxes application wide.

Application hook:

EventManager.RegisterClassHandler(typeof(ComboBox), UIElement.PreviewMouseLeftButtonDownEvent, new MouseButtonEventHandler(FixComboBoxOutClick));

Handler code:

    private void FixComboBoxOutClick(object sender, MouseButtonEventArgs e) {
        if (sender is ComboBox combo) {
            Point comboRelativePoint = Mouse.GetPosition(combo);
            if (comboRelativePoint.X < 0 || comboRelativePoint.Y < 0 || comboRelativePoint.X > combo.ActualWidth || comboRelativePoint.Y > combo.ActualHeight) {
                UIElement popupContent = combo.FindChild<Popup>(null).Child;
                Point popupRelativePoint = Mouse.GetPosition(popupContent);
                if (popupRelativePoint.X < 0 || popupRelativePoint.Y < 0 || popupRelativePoint.X > popupContent.RenderSize.Width || popupRelativePoint.Y > popupContent.RenderSize.Height) {
                    combo.IsDropDownOpen = false;
                }
            }
        }
    }

You can look for FindChild<T>() implementations here.

like image 94
LoRdPMN Avatar answered Oct 22 '25 19:10

LoRdPMN



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!