0

1- Copy and paste the following code into MainWindow.xaml file.

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <TextBox x:Name="TextBox1" Height="25" Width="200" Background="Yellow" MouseEnter="TextBox1_MouseEnter" MouseLeave="TextBox1_MouseLeave"/>
    <Popup x:Name="Popup1" IsOpen="False" StaysOpen="True" AllowsTransparency="True" PlacementTarget="{Binding ElementName=TextBox1}" Placement="Bottom">
        <Label Background="Yellow" Content="Hi stackoverflow"/>
    </Popup>
</Grid>
</Window>

2- Copy and paste the following code into MainWindow.xaml.cs file.

namespace WpfApplication1
{
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

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

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

3- You will see that Popup1 opens properly when you put your mouse on TextBox1.

My question is here;

I dont want Popup1 opens as soon as you put your mouse on TextBox1.

In other words I want Popup1 opens if User put his mouse on TextBox1 at least one second.

You know that ToolTip doesnt open as soon as you put your mouse.

So I want ToolTip behavior for Popup1.

1 Answers1

1

Go ahead and add using System.Timers; Now, initialize a timer in your constructor, and add a handler to the Elapsed event:

private Timer t;
public MainWindow()
{
    InitializeComponent();
    t = new Timer(1000);
    t.Elapsed += Timer_OnElapsed;
}

private void Timer_OnElapsed(object sender, ElapsedEventArgs e)
{
    Application.Current.Dispatcher?.Invoke(() =>
    {
        Popup1.IsOpen = true;
    });
}

We defined a timer to count down one second and open the popup when finished. We are calling the dispatcher to open the popup because this code will be executed from a different thread.

Now, the mouse events:

private void TextBox1_MouseEnter(object sender, MouseEventArgs e)
{
    t.Start();
}

private void TextBox1_MouseLeave(object sender, MouseEventArgs e)
{
    t.Stop();
    Popup1.IsOpen = false;
}

The timer will start when the mouse enters the TextBox and stop (and reset) and the popup will close when the mouse leaves.

Efi Z
  • 182
  • 12
  • 1
    **@Efi Z** Thanks. Your code works. I am waiting other answers if there is simpler code. – Michael Scofield Nov 17 '19 at 16:07
  • 2
    Simpler would be a `DispatcherTimer`. It would eliminate the need for calling `Dispatcher.Invoke`. See [this answer](https://stackoverflow.com/a/2053885/1136211) to the original question. You won't typically use `System.Timers.Timer` at all in a WPF application. – Clemens Nov 17 '19 at 16:25