Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 向MouseLeave情节提要添加延迟_C#_Wpf_Storyboard_Delay_Mouseleave - Fatal编程技术网

C# 向MouseLeave情节提要添加延迟

C# 向MouseLeave情节提要添加延迟,c#,wpf,storyboard,delay,mouseleave,C#,Wpf,Storyboard,Delay,Mouseleave,我有一个故事板,当为特定控件触发MouseLeave时播放动画 我想在触发MouseLeave后引入500毫秒的延迟,并检查鼠标是否不再位于控件上方。然后才播放控制。如果用户在500毫秒内将鼠标移回控件上,我不需要播放情节提要动画。如何实现这一点?设置一个标志bool isMouseOver=true。在MouseLeave上,将标志设置为false,在MouseEnter上,将其设置为true。创建一个方法,如果isMouseOver==false,则触发动画,并以500毫秒的延迟将其附加到计

我有一个故事板,当为特定控件触发
MouseLeave
时播放动画


我想在触发
MouseLeave
后引入500毫秒的延迟,并检查鼠标是否不再位于控件上方。然后才播放控制。如果用户在500毫秒内将鼠标移回控件上,我不需要播放情节提要动画。如何实现这一点?

设置一个标志
bool isMouseOver=true
。在
MouseLeave
上,将标志设置为
false
,在
MouseEnter
上,将其设置为
true
。创建一个方法,如果
isMouseOver==false,则触发动画,并以500毫秒的延迟将其附加到计时器。计时器本身应在
MouseLeave
事件时启动/重置,并在
MouseEnter
事件时停止

编辑:
当然,如果可用,您应该使用
IsMouseOver
属性而不是自定义标志。

代码可以满足您的要求

private void UIElement_OnMouseLeave(object sender, MouseEventArgs e)
{
    var uiElement = sender as UIElement;
    uiElement.MouseLeave -= UIElement_OnMouseLeave;

    Task.Factory.StartNew(() =>
    {
        Thread.Sleep(1000); // or 500ms
        Dispatcher.Invoke(() =>
        {
            if (!uiElement.IsMouseOver)
            {
                // Animation Code Goes Here;
            }
            uiElement.MouseLeave += UIElement_OnMouseLeave;
        });
    });
}
根据Tarec的需求

private readonly DispatcherTimer _dispatcherTimer = new DispatcherTimer
{
    Interval = new TimeSpan(0,0,0,0,1000),
};

_dispatcherTimer.Tick += (sender, args) =>
{
    _dispatcherTimer.Stop();
    if (!uIElement.IsMouseOver)
    {
        // Animation Code Goes Here;
    }
};

private void UIElement_OnMouseLeave(object sender, MouseEventArgs e)
{
    // Reset Timer if Mouse Leave
    _dispatcherTimer.Stop();
    _dispatcherTimer.Start();
}

对象强制转换为
并进行非空检查是不可接受的。另外,我认为每次鼠标返回uiElement时,应该停止/重置触发该方法。在你的答案中,它只在第一次出现在MouseLeave
上的1000毫秒后被检查一次,因此在1000毫秒内用鼠标指针返回和离开被忽略。@塔瑞克我编辑了我的答案谢谢穆贾希德的好答案,我无法更好地解决它。为什么我们需要
\u dispatchTimer.Stop()
在OnMouseLeave内,当它已作为勾选的一部分停止时?我不理解这一部分,你能澄清一下吗?我接受了这一攻击,这是代码1和代码2的唯一区别,因为如果鼠标离开而不是中间值,计时器将从0重新启动。这都可以在xaml中完成。只需将故事板的开始时间设置为00:00:00.5,并在鼠标进入控件时停止故事板。