以下是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);
以下是触发动画的辅助方法:
/// <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);
}
除了两个问题外,代码效果很好:
为什么会这样?如何在没有黑色背景故障的情况下使这个动画顺利运行?
答案 0 :(得分:6)
您需要在AllowsTransparency
上将true
设置为Window
,以使其完全透明。
不幸的是,只有WindowStyle=None
才能实现这一点,因此您必须实现自己的标题栏。
这会带来一些讨厌的性能问题,因为窗口不能再进行硬件渲染了。如果你这样做,我强烈建议在UI线程上将RenderOptions.ProcessRenderMode
设置为RenderMode.SoftwareOnly
(.NET 4.0或更高版本),以便在简单的合成中获得可接受的性能。