WPF DispatcherFrame魔法-它是如何以及为什么工作的

本文关键字:为什么 工作 魔法 DispatcherFrame WPF | 更新日期: 2023-09-27 18:16:37

我试图在WPF中动画一些东西,并在动画完成时运行一些其他操作。

同时,想要避免动画完成回调机制,所以,我想出了一个解决方案,如下面的代码所示:

// Start one second of animation
...
// Pause for one second
Wait(this.Dispatcher, 1000);
// Continue and do some other stuff
...
现在,有趣的部分是Wait方法,其中神奇地使阻塞暂停在我的代码,但动画和UI保持正常,响应:
    public static void Wait(Dispatcher Dispatcher, int Milliseconds)
    {
        var Frame = new DispatcherFrame();
        ThreadPool.QueueUserWorkItem(State =>
        {
            Thread.Sleep(Milliseconds);
            Frame.Continue = false;
        });
        Dispatcher.PushFrame(Frame);
    }

我已经阅读了关于DispatcherFrame的文档和几篇文章,但我仍然无法弄清楚到底发生了什么,我需要澄清一下PushFrame的这种结构是如何真正工作的。

WPF DispatcherFrame魔法-它是如何以及为什么工作的

From MSDN:

PushFrame

进入执行循环。

只要Continue属性为true,循环(即DispatcherFrame)就会执行。

一旦Continue属性变为false,循环/帧就退出,Dispatcher返回到调用PushFrame之前执行的循环/帧。

如果你想暂停一下,为什么不这样做呢?

private async void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
    var btn = sender as Button;
    btn.Content = "Before pause";
    var animation = new DoubleAnimation();
    animation.From = btn.ActualWidth;
    animation.To = 100;
    animation.Duration = TimeSpan.FromSeconds(2);
    btn.BeginAnimation(Button.WidthProperty, animation);
    await Task.Delay(2000);
    btn.Content = "After pause";
}
相关文章: