I have a storyboard plays an animation when the MouseLeave is triggered for the particular control.

I want to introduce a delay of 500 millisecond after MouseLeave is triggered and check if the mouse is no longer over the control. Only then play the control. If the user has brought back the mouse over the control within 500 millisecond I need not play the storyboard animation. How to achieve this?

有帮助吗?

解决方案

Code to Achieve your Requirement

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

OR on Demand for 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();
}

其他提示

Set a flag bool isMouseOver = true. On MouseLeave set a flag to false and on MouseEnter set it to true. Create yourself a method that fires animation if isMouseOver == false and attach it to the timer with 500ms delay. The timer itself should be started/reseted on MouseLeave event and stopped on MouseEnter.

edit: Of course you should use IsMouseOver property instead of custom flag if available.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top