.NET WPF窗口FadeIn和FadeOut动画

c0D*_*g1c 3 .net wpf animation window

下面是窗口FadeIn和FadeOut动画的代码片段:

// Create the fade in storyboard
fadeInStoryboard = new Storyboard();
fadeInStoryboard.Completed += new EventHandler(fadeInStoryboard_Completed);
DoubleAnimation fadeInAnimation = new DoubleAnimation(0.0, 1.0, new Duration(TimeSpan.FromSeconds(0.30)));
Storyboard.SetTarget(fadeInAnimation, this);
Storyboard.SetTargetProperty(fadeInAnimation, new PropertyPath(UIElement.OpacityProperty));
fadeInStoryboard.Children.Add(fadeInAnimation);

// Create the fade out storyboard
fadeOutStoryboard = new Storyboard();
fadeOutStoryboard.Completed += new EventHandler(fadeOutStoryboard_Completed);
DoubleAnimation fadeOutAnimation = new DoubleAnimation(1.0, 0.0, new Duration(TimeSpan.FromSeconds(0.30)));
Storyboard.SetTarget(fadeOutAnimation, this);
Storyboard.SetTargetProperty(fadeOutAnimation, new PropertyPath(UIElement.OpacityProperty));
fadeOutStoryboard.Children.Add(fadeOutAnimation);
Run Code Online (Sandbox Code Playgroud)

以下是触发动画的辅助方法:

/// <summary>
/// Fades the window in.
/// </summary>
public void FadeIn()
{
   // Begin fade in animation
   this.Dispatcher.BeginInvoke(new Action(fadeInStoryboard.Begin), DispatcherPriority.Render, null);
}

/// <summary>
/// Fades the window out.
/// </summary>
public void FadeOut()
{
   // Begin fade out animation
   this.Dispatcher.BeginInvoke(new Action(fadeOutStoryboard.Begin), DispatcherPriority.Render, null);
}
Run Code Online (Sandbox Code Playgroud)

除了两个问题外,代码工作得很好:

  1. 在FadeIn()上,窗口以丑陋的黑色背景开始,然后正确动画.
  2. 在FadeOut()上正确设置动画,然后窗口以丑陋的黑色背景结束.

为什么会这样?如何在没有黑色背景故障的情况下使这个动画顺利运行?

MrD*_*osu 6

您需要设置AllowsTransparencytrueWindow它从完全透明上来.

不幸的是,这只能用WindowStyle=None,所以你必须实现自己的标题栏.

这带来了一些讨厌的性能问题,因为窗口不能再进行硬件渲染.如果你这样做,我强烈建议在UI线程上设置RenderOptions.ProcessRenderModeRenderMode.SoftwareOnly(.NET 4.0或更高版本),以便在简单的合成中获得可接受的性能.