Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
680 views
in Technique[技术] by (71.8m points)

wpf - Combobox popup blocks mouse/touch events from rest of application

I've searched this topic all over, and even though I imagine this might be an issue many developers came across, I couldn't find anything relating to it (sorry if I missed something and this is a duplicate).

Whenever the user opens the dropdown of a Combobox, the rest of the application doesn't respond before closing the dropdown. So for example when you click on a button outside the combobox, it will close the dropdown without triggering the button, and only the second click will trigger it.

My first thought was that the popup element blocks the MouseDown (or even MouseOver) event since it's in a separate visual tree, but even after customizing the combobox and adding a border with opacity change when opened (so it's in the same visual tree), this phenomenon still occur.

If anyone has any thoughts on how to go around this behavior I would really appreciate it.

The image is just to demonstrate that while the dropdown is open, MouseOver on the button doesn't fire


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want the item list to close automatically when the mouse is leaving the item list, without having to click outside the list, you can get a reference to the Popup element in the Combobox template and take control of its MouseLeave event. When you set the IsOpen to false, it will close automatically and leave the control of the mouse to the main window.

XAML:

        <ComboBox Name="comboBox" Margin="5" Width="100" DropDownOpened="comboBox_DropDownOpened"/>

Code behind:

    Popup popup = null;

    private void comboBox_DropDownOpened(object sender, EventArgs e)
    {
        if (popup == null)
        {
            popup = (Popup)comboBox.Template.FindName("PART_Popup", comboBox);
            popup.MouseLeave += Popup_MouseLeave;
        }
    }

    private void Popup_MouseLeave(object sender, MouseEventArgs e)
    {
        ((Popup)sender).IsOpen = false;
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...