一秒钟后如何触发MouseEnter事件

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 stackoverflow"/>
    </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 上时,您会看到 Popup1 正确打开。

我的问题在这里;

将鼠标放在 TextBox1 上时,我不希望 Popup1 打开。

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

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

所以我想要 Popup1 ToolTip 行为。

shanlinghai 回答:一秒钟后如何触发MouseEnter事件

继续并添加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;
}

当鼠标进入文本框时计时器开始计时,然后停止(并重置),当鼠标离开时弹出窗口将关闭。

本文链接:https://www.f2er.com/3085941.html

大家都在问