首页 > 解决方案 > 当我使用计时器时 UI 阻塞

问题描述

我尝试用动画在我的窗口中移动一个网格,但动画没有发生,所以我放了一个计时器,这样你就可以一点一点地看到动画,但它仍然不起作用:/

这是我的代码:

class Animation
{
    private int x_dropGridToBottom;
    private Grid grid_dropGridToBottom;
    private System.Timers.Timer t;

    public Animation()
    {
        t = new System.Timers.Timer();
        t.Interval = 500;
    }

    private void TimerElapsed_DropGridToBottom(object sender, ElapsedEventArgs e)
    {
        while (x_dropGridToBottom > 0)
        {
            x_dropGridToBottom--;

            Application.Current.Dispatcher.Invoke(() =>
            {
                grid_dropGridToBottom.Margin = new Thickness(0, x_dropGridToBottom, 0, x_dropGridToBottom);
            });
        }
        if (x_dropGridToBottom == 0)
            t.Stop();
    }

    internal void DropGridToBottom(Grid grid, Window window)
    {
        grid.Margin = new Thickness(0, window.Height, 0, window.Height);

        // 0 x 0 x (x = window.height)
        // x = -y (y=412)
        // x (=) 0

        grid_dropGridToBottom = grid;
        x_dropGridToBottom = Convert.ToInt32(window.Height);

        t.Elapsed += new ElapsedEventHandler(TimerElapsed_DropGridToBottom);
        t.Start();
    }
}

这是我按下应该启动动画的按钮时的代码:

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        Animation anim = new Animation();
        anim.DropGridToBottom(grid_2, this);
    }

有人知道为什么以及如何让我的网格一点一点地移动,但不能一次直接移动(就像现在一样)。

谢谢

标签: c#animationgrid

解决方案


推荐阅读