下面是窗口淡入淡出动画的代码片段:
// 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);
下面是触发动画的辅助方法:
/// <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);
}
除了两个问题外,代码运行良好:
- 在 FadeIn() 上,窗口以丑陋的黑色背景开始,然后正确设置动画。
- 在 FadeOut() 上正确设置动画,然后窗口以丑陋的黑色背景结束。
为什么会这样?如何使此动画流畅运行而没有黑色背景问题?
最佳答案
您需要在 Window
上将 AllowsTransparency
设置为 true
以使其完全透明。
不幸的是,这只能通过 WindowStyle=None
实现,因此您必须实现自己的标题栏。
这带来了一些严重的性能问题,因为窗口不能再被硬件渲染了。如果您这样做,我强烈建议在 UI 线程上将 RenderOptions.ProcessRenderMode
设置为 RenderMode.SoftwareOnly
(.NET 4.0 或更高版本),以便在简单的组合中获得可接受的性能。
关于.NET WPF 窗口淡入淡出动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3766999/