title: .NET WPF Window FadeIn and FadeOut Animation
body: <p>Below is code snippets of a window FadeIn and FadeOut animation:</p>
  
  <pre><code>// 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);
  </code></pre>
  
  <p>Below are the helper methods which trigger the animation:</p>
  
  <pre><code>/// &lt;summary&gt;
  /// Fades the window in.
  /// &lt;/summary&gt;
  public void FadeIn()
  {
     // Begin fade in animation
     this.Dispatcher.BeginInvoke(new Action(fadeInStoryboard.Begin), DispatcherPriority.Render, null);
  }
  
  /// &lt;summary&gt;
  /// Fades the window out.
  /// &lt;/summary&gt;
  public void FadeOut()
  {
     // Begin fade out animation
     this.Dispatcher.BeginInvoke(new Action(fadeOutStoryboard.Begin), DispatcherPriority.Render, null);
  }
  </code></pre>
  
  <p>The code works great except for two problems:</p>
  
  <ol>
  <li>On FadeIn() the window starts off with an ugly black background then animates correctly.</li>
  <li>On FadeOut() animates correctly then the window ends off with an ugly black background.</li>
  </ol>
  
  <p>Why is this happening? How do i make this animation run smoothly without the black background hitch?</p>