2010-09-22 101 views
2

下面是一個窗口,淡入淡出和動畫的代碼片段:.NET WPF窗口淡入淡出和動畫

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

代碼工作除了兩個問題:

  1. 在FadeIn()窗口開始與一個醜陋的黑色背景然後正確動畫。
  2. 在FadeOut()上正確動畫,然後窗口以醜陋的黑色背景結束。

這是怎麼發生的?如何在沒有黑色背景的情況下讓動畫順利運行?

回答

5

您需要在Window上設置AllowsTransparencytrue,以使其完全透明。

不幸的是,這隻適用於WindowStyle=None,所以你必須實現自己的標題欄。

這帶來了一些令人討厭的性能問題,因爲該窗口不能再被硬件渲染。如果你這樣做,我強烈建議在UI線程上設置RenderOptions.ProcessRenderModeRenderMode.SoftwareOnly(.NET 4.0或更高版本)以獲得可接受的簡單組合作品。

+0

你好MrDosu。感謝你的回答。我使用自定義的WPF窗口,因爲這樣的WindowStyle = None proeprty已經設置。將設置RenderOptions.SoftwareOnly性能增益。我在VS 2010 .NET 4.0中:) – c0D3l0g1c 2010-09-22 07:46:42

+1

可以在Windows Vista或更高版本上渲染分層的Windows(WindowStyle = None,AllowsTransparency = True,Background = Transparent)。 – 2011-01-26 12:53:40