Smooth animations, at the Window level

If you have ever tried animating the Width / Height of a Window control, you would notice some jerkiness during the animation. This happens because the Window control is not really living entirely in the WPF sandbox. It is part WPF and part Native. To achieve a really smooth animation, you have GOT TO BE inside the WPF sandbox. But how do I do it?

The AnimationWindow

Creating animations directly on the Window is definitely not a desired solution. You have to first push the window contents (both the client-area and the non-client-area) into the WPF sandbox. You can do this by deriving from the GlassWindow control. You can create very customized ControlTemplates and replicate the look of a native window. You also have the flexibility of completely changing the look and feel of your application windows. This is a first step towards moving the Window content into the WPF sandbox.

However you still have the same problem when it comes to animating the window. That is because the GlassWindow is still using the native window wrapper and animating its Width / Height would still cause the jerkiness. What we need to do is push the entire window contents into a WPF control and then animate that control.

This is exactly what the AnimationWindow does. It derives from GlassWindow and overrides its OnApplyTemplate() method. Inside the override it caches a reference to the top level container that contains the complete window contents (client + non-client). When you trigger resizing animations on the Window, the actual animation happens on this container. Since you are completely inside the WPF sandbox, the animations are smooth and your customers happy ;-).

So what’s the Trick ?

[1] Derive from GlassWindow and override OnApplyTemplate()

 1 [TemplatePart(Type = typeof(Grid), Name = "PART_WindowContent")]
 2 public class AnimationWindow : GlassWindow
 3 {
 4     private Grid _contentGrid;
 5 
 6     private Storyboard _resizeAnimator;
 7 
 8     public static readonly DependencyProperty NewSizeProperty = DependencyProperty.Register(
 9 
10     "NewSize", typeof(Size), typeof(AnimationWindow), new PropertyMetadata(new Size()));
11 
12     public Size NewSize
13     {
14 
15         get { return (Size)GetValue(NewSizeProperty); }
16 
17         set { SetValue(NewSizeProperty, value); }
18 
19     }
20 
21     static AnimationWindow()
22     {
23 
24         DefaultStyleKeyProperty.OverrideMetadata(typeof(AnimationWindow),
25 
26         new FrameworkPropertyMetadata(typeof(AnimationWindow)));
27 
28     }
29 
30     public override void OnApplyTemplate()
31     {
32 
33         base.OnApplyTemplate();
34 
35         // Get a reference to the ContentGrid
36 
37         _contentGrid = GetChildControl & lt; Grid & gt; ("PART_WindowContent");
38 
39     }
40 
41 }
Before starting the animation you need to set the NewSize DependencyProperty. The GetChildControl is a protected method on GlassWindow. Inside OnApplyTemplate() I am caching the top-level container as _contentGrid.

[2] Expose a method to animate window

 1 public void ApplyResizeAnimation()
 2 {
 3     Size currentSize = new Size(Width, Height);
 4     // Temporarily resize the ContentGrid to avoid automatic layout flashes
 5     _contentGrid.SetValue(WidthProperty, currentSize.Width);
 6     _contentGrid.SetValue(HeightProperty, currentSize.Height);
 7     if (NewSize.Width > currentSize.Width)
 8     {
 9         Width = NewSize.Width;
10     }
11 
12     if (NewSize.Height > currentSize.Height)
13     {
14         Height = NewSize.Height;
15     }
16 
17     PlayAnimation(currentSize);
18 }
19 
20 private void PlayAnimation(Size currentSize)
21 {
22     // Create Storyboard
23     _resizeAnimator = PrepareStoryboard(currentSize);
24     _resizeAnimator.CurrentStateInvalidated += ResizeAnimator_CurrentStateInvalidated;
25     _resizeAnimator.Begin(_contentGrid, true);
26 }
27 
28 void ResizeAnimator_CurrentStateInvalidated(object sender, EventArgs e)
29 {
30     Clock clock = sender as Clock;
31     if (clock.CurrentState != ClockState.Active)
32     {
33         Width = NewSize.Width;
34         Height = NewSize.Height;
35         // Clear Width/Height settings and switch to automatic layout
36         _contentGrid.ClearValue(WidthProperty);
37         _contentGrid.ClearValue(HeightProperty);
38         _resizeAnimator.CurrentStateInvalidated -= ResizeAnimator_CurrentStateInvalidated;
39         _resizeAnimator.Remove(_contentGrid);
40     }
41 }
42 
43 private Storyboard PrepareStoryboard(Size size)
44 {
45     Storyboard board = new Storyboard();
46     board.FillBehavior = FillBehavior.HoldEnd;
47 
48     // Width
49     DoubleAnimation wAnim = new DoubleAnimation(size.Width, NewSize.Width,
50     new Duration(TimeSpan.FromMilliseconds(500)));
51     Storyboard.SetTargetProperty(wAnim, new PropertyPath("(0)", WidthProperty));
52 
53     // Height
54     DoubleAnimation hAnim = new DoubleAnimation(size.Height, NewSize.Height,
55     new Duration(TimeSpan.FromMilliseconds(500)));
56     Storyboard.SetTargetProperty(hAnim, new PropertyPath("(0)", HeightProperty));
57 
58     board.Children.Add(wAnim);
59     board.Children.Add(hAnim);
60 
61     return board;
62 }
63 	
In ApplyResizeAnimation() I first explicitly set the Width + Height of the _contentGrid. I do this to avoid some automatic layout flashes. These would happen if my NewSize is greater than the current size. I then clear the explicit Width + Height settings when the animation gets over. Note that I am exploiting the precedence nature of the DependencyProperty.

[3] Create a ControlTemplate for the Window with transparency

 1 <Style x:Key="TestWindowStyle"
 2              TargetType="{x:Type Controls:AnimationWindow}">
 3     <Setter Property="AllowsTransparency"
 4                     Value="True"/>
 5     <Setter Property="WindowStyle"
 6                     Value="None"/>
 7     <Setter Property="ResizeMode"
 8                     Value="CanResize"/>
 9     <Setter Property="Template"
10                     Value="{StaticResource TestWindow_Template}"/>
11 </Style>
With all of these, your animations should run super smooth!

Getting Creative

Note that you can pull off some really exotic tricks with the AnimationWindow. Right now the resize animations are hard-coded. You can change that to expose a property on AnimationWindow to set custom Storyboards. If you club it with the TransitionContainer, you can even have Mac OSX style genie effects, right on the Desktop !!

Download EXE