user589195
user589195

Reputation: 4240

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

Upvotes: 2

Views: 6783

Answers (3)

Mikey
Mikey

Reputation: 11

Put the mouse leave event on the data grid instead of on the popup

<Popup Name="myPopup" IsOpen="False" PlacementTarget="{Binding ElementName=myButton}" StaysOpen="False">
    <DataGrid MinHeight="400" MinWidth="300" Name="dtgPopup" AutoGenerateColumns="False" ItemsSource="{Binding}" SelectionChanged="dtgPopup_SelectionChanged"  IsReadOnly="True" CanUserAddRows="False"
               MouseLeave="myPopup_MouseLeave">
</DataGrid>

Upvotes: 0

Amadeus Hein
Amadeus Hein

Reputation: 716

You could handle this solely in wpf if you wish, depending on how clean you want to keep you code behind. This way you can use IsMouseOver instead of detecting MouseLeave/MouseEnter.

Use a MultiDataTrigger in the TextBlock triggers resources like this:

<MultiDataTrigger>
  <MultiDataTrigger.Conditions>
    <Condition
      Binding="{Binding Mode=OneWay, RelativeSource={RelativeSource Self}, Path=IsMouseOver}" 
      Value="True"
  />
  </MultiDataTrigger.Conditions>
  <Setter
    TargetName="myPopup" 
    Property="IsOpen" 
    Value="True" 
  />
</MultiDataTrigger>

Upvotes: 4

Nomad101
Nomad101

Reputation: 1698

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

Upvotes: 2

Related Questions