下面是窗口淡入和淡出动画的代码片段:
// 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() 动画正确时,窗口会以丑陋的黑色背景结束。
为什么会发生这种情况?如何使该动画流畅运行而不会出现黑色背景问题?
你需要设置AllowsTransparency
to true
on the Window
让它完全透明。
不幸的是,这只能通过WindowStyle=None
,因此您必须实现自己的标题栏。
这会带来一些严重的性能问题,因为窗口无法再进行硬件渲染。如果你走这条路我强烈建议设置RenderOptions.ProcessRenderMode
to RenderMode.SoftwareOnly
(.NET 4.0 或更高版本)在 UI 线程上,以便在简单的组合中获得可接受的性能。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)