Search code examples
c#wpfevents

Closing wpf popup when mouse leaves


I have a label whose mouseover event opens up a popup.

I am trying to handle the mouseleave event on the popup window and close the popup down.

The problem I'm having is that the mouseleave event is not getting fired until I click anywhere outside the popup window.

Could someone advise me as to what Im doing wrong?

Heres the code.

XAML:

<Popup Name="myPopup" IsOpen="False" PlacementTarget="{Binding ElementName=myButton}" StaysOpen="False" MouseLeave="myPopup_MouseLeave">

    <DataGrid MinHeight="400" MinWidth="300" Name="dtgPopup" AutoGenerateColumns="False" ItemsSource="{Binding}" SelectionChanged="dtgPopup_SelectionChanged"  IsReadOnly="True" CanUserAddRows="False">

    </DataGrid>

</Popup>

<Label Name="recentPanels" Content="Recent Panels" MouseEnter="recentPanels_MouseEnter"/>

Event Handlers:

private void recentPanels_MouseEnter(object sender, MouseEventArgs e)
        {
            myPopup.IsOpen = true;
        }

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

Solution

  • From my experience it seems to need the mouse click to realize that the mouse pointer has actually left the form or popup. A work around that is simple to implement is as follows, instead of using the MouseLeave event use the OnMouseLeave.

    protected virtual void OnMouseLeave(MouseEventArgs e)
    {
        myPopup.IsOpen = false;
    }
    

    Some more information: http://msdn.microsoft.com/en-us/library/system.windows.controls.control.onmouseleave(v=vs.95).aspx