简体   繁体   中英

How to display a stack panel after some delay on button hover in WPF?

I have one button, on hovering mouse on that button for two seconds, i want open the stack panel.

xaml code:

<StackPanel x:Name="spPinDetailsPopup" Height="200" Width="240" Visibility="Hidden">
     <!--it contains label control which have text to display-->
</StackPanel>
<Button x:Name="btnDisplayPopUp" MouseEnter="DisplayPopUpOnMouseEnter"/>

CS code :

void DisplayPopUpOnMouseEnter(object sender, MouseEventArgs e)
{
    spPinDetailsPopup.Visibility = Visibility.Visible;
}

I have used the stack panel as a pop up which displays the control information.

Current Result : Stack panel is displayed immediately.

Expected Result : Stack panel should only be open when we put mouse cursor on button for more than 2 seconds. Is there any solution ?

Why not use ToolTip ?

    <Button ToolTip="Some Text" ToolTipService.InitialShowDelay="2000"/>

As ToolTip is an object , you can configure the layout to whatever you like, not just some text.

https://docs.microsoft.com/en-us/dotnet/framework/wpf/controls/tooltip-overview

Solution :

I created one DispatcherTimer object at global level to controlling the time interval to open the popup.

private static DispatcherTimer _popUpOpeningTimer = new DispatcherTimer();

void DisplayPopUpOnMouseEnter(object sender, MouseEventArgs e)
{
    // if we do not have DispatcherTimer set then only initialize it 
    if (_popUpOpeningTimer == null)
    {
          _popUpOpeningTimer = new DispatcherTimer();
    }
    else // this means that dispatcher timer is already initialized, so do nothing
    {
         // do nothing
    }
    // stop the timer if it is already set so that we can start new timer
    _popUpOpeningTimer.Stop();

    _popUpOpeningTimer.Interval = new TimeSpan(0, 0, 1);

    _popUpOpeningTimer.Tick += new EventHandler((senderObject, eventArguments) => DisplayPopUp(senderObject, eventArguments, btnDisplayPopUp));

    // start the timer for opening the details popup
    _popUpOpeningTimer.Start();  
}

private void DisplayPopUp(object sender, EventArgs e, Button button)
{
    if(button.IsMouseOver)
    {
         spPinDetailsPopup.Visibility = Visibility.Visible;
    }
    else
    {
         // do nothing
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM