如何在一秒后触发 MouseEnter 事件

How to trigger MouseEnter Event after one second

1- 将以下代码复制并粘贴到 MainWindow.xaml 文件中。

<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 Whosebug"/>
    </Popup>
</Grid>
</Window>

2- 将以下代码复制并粘贴到 MainWindow.xaml.cs 文件中。

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- 当您将鼠标放在 TextBox1[=45= 上时,您会看到 Popup1 正常打开].

我的问题在这里;

我不希望 Popup1 在您将鼠标放在 TextBox1.

上时立即打开

换句话说,如果用户将鼠标放在 TextBox1 至少一秒钟,我希望 Popup1 打开 .

您知道 工具提示 不会在您放置鼠标时立即打开。

所以我想要 ToolTip Popup1 的行为。

继续添加 using System.Timers; 现在,在构造函数中初始化一个计时器,并向 Elapsed 事件添加一个处理程序:

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

我们定义了一个计时器来倒计时一秒并在完成时打开弹出窗口。 我们正在调用调度程序打开弹出窗口,因为这段代码将从不同的线程执行。

现在,鼠标事件:

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

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

计时器将在鼠标进入 TextBox 时启动并停止(并重置),弹出窗口将在鼠标离开时关闭。