Search code examples
c#wpfpopup.net-4.5

Popup window gets flickering quickly when I hold on the mouse on it for some time (without moving mouse)


I have an WPF Popup which I apply to a WPF Label:

<Style x:Key="myPopupStyle" TargetType="{x:Type ContentControl}">
    <Setter Property="ContentTemplate">
        <Setter.Value>
            <DataTemplate>
                  <!-- Here the data template -->
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>

<Label x:Name="myLabel"
               MouseEnter="myLabel_ShowTooltip"
               MouseLeave="myLabel_CloseTooltip">

<Popup x:Name="tooltipPopupMyLabel"
               AllowsTransparency="True"
               StaysOpen="False"
               UseLayoutRounding="True"
               PlacementTarget="{Binding ElementName=myLabel}"
               Placement="Bottom">
        <ContentControl Content="this is a tooltip popup!" Style="{StaticResource myPopupStyle}"/>
</Popup>

And the event handlers below:

    private void myLabel_ShowTooltip(object sender, System.Windows.Input.MouseEventArgs e)
    {
        if (!this.tooltipPopupMyLabel.IsOpen)
        {
            this.tooltipPopupMyLabel.IsOpen = true;
            // If I uncomment below line of code it stops flickering.
            //this.tooltipPopupMyLabel.StaysOpen = true;
        }
    }

    private void myLabel_CloseTooltip(object sender, System.Windows.Input.MouseEventArgs e)
    {
        if (this.tooltipPopupMyLabel.IsOpen)
        {
            this.tooltipPopupMyLabel.IsOpen = false;
            //this.tooltipPopupMyLabel.StaysOpen = false;
        }
    }

When I hold on the mouse on the label, the tooltip popup is shown fine but if I keep the mouse on it without moving it for some time, I can see that it is producing flickering, it looks like popup is being closed and reopened quickly.

If in the myLabel_ShowTooltip I uncomment the line this.tooltipPopupMyLabel.StaysOpen = true; then no flickering is produced. Why I get this flickering if I don't set StaysOpen=true?


Solution

  • put Label and Popup in the same container and use container's mouse events:

    <Grid Background="Transparent"
          MouseEnter="myLabel_ShowTooltip"
          MouseLeave="myLabel_CloseTooltip">
        <Label x:Name="myLabel"/>
        
        <Popup x:Name="tooltipPopupMyLabel"
                       AllowsTransparency="True"
                       StaysOpen="True"
                       UseLayoutRounding="True"
                       PlacementTarget="{Binding ElementName=myLabel}"
                       Placement="Bottom">
                <ContentControl Content="this is a tooltip popup!" Style="{StaticResource myPopupStyle}"/>
        </Popup>
    </Grid>
    

    you can also try discrete animations instead of event handlers, like shown in this Q&A