2014-02-18 33 views
0

我有一个故事板播放动画时MouseLeave触发了特定的控制。添加延迟鼠标离开故事板

我想MouseLeave被触发后,引入500毫秒的延迟,并检查鼠标在控制不再。只有然后播放控件。如果用户在500毫秒内将鼠标移回控件上,我不需要播放故事板动画。如何实现这一目标?

+0

这都可以在XAML来完成。只需将故事板的开始时间设置为00:00:00.5,并在鼠标进入控制时停止故事板。 – Silvermind

回答

2

代码来实现您的要求

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(); 
} 
+0

使用'as'铸造对象而不是null-检查它是不可接受的。另外 - 我认为每次鼠标返回到uiElement时,应该停止/重置触发该方法。在你的答案中,只有在第一次出现“OnMouseLeave”1000毫秒后才检查一次,所以在这1000毫秒内退出并用鼠标指针去掉会被忽略。 – Tarec

+0

@Tarec我编辑了我的答案 –

+1

我现在将其标记为答案。 – Tarec

0

设置一个标志​​。在MouseLeave上设置标志为false,在MouseEnter上设置为true。创建一个方法,如果isMouseOver == false触发动画,并将其附加到具有500ms延迟的定时器。计时器本身应该在MouseLeave事件上启动/复位,并在MouseEnter上停止。

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