开发者

.NET WPF Window FadeIn and FadeOut Animation

Below is code snippets of a window FadeIn and FadeOut animation:

// 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_Com开发者_JAVA百科pleted);
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);

Below are the helper methods which trigger the animation:

/// <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);
}

The code works great except for two problems:

  1. On FadeIn() the window starts off with an ugly black background then animates correctly.
  2. On FadeOut() animates correctly then the window ends off with an ugly black background.

Why is this happening? How do i make this animation run smoothly without the black background hitch?


You would need to set AllowsTransparency to true on the Window for it to come up from fully transparent.

Unfortunately this is only possible with WindowStyle=None, so you would have to implement your own title bar.

This brings forth some nasty performance issues, since the window cannot be hardware rendered anymore. If you go this way I strongly suggest setting RenderOptions.ProcessRenderMode to RenderMode.SoftwareOnly (.NET 4.0 or higher) on the UI thread to get acceptable performance in simple compositions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜