I'm trying to resize a WPF window using Storyboard
. My code works perfectly when I animate the window width or height, but when I'm applying a storyboard on both of them it animates only the first property (width in my case) and skips on the second one.
My code is:
private void AnimateWindowSize(double width, double height, bool isRelative = false)
{
//---------------------------------------------------
// Settings
//---------------------------------------------------
var duration = TimeSpan.FromSeconds(0.2);
var newWidth = isRelative ? this.Width - width : width;
var newHeight = isRelative ? this.Height - height : height;
Console.WriteLine($"Animating window from {this.Width}x{this.Height} to {newWidth}x{newHeight}");
this.Dispatcher.BeginInvoke(new Action(() =>
{
var storyboard = new Storyboard();
//---------------------------------------------------
// Animate Width
//---------------------------------------------------
var widthAnimation = new DoubleAnimation()
{
Duration = new Duration(duration),
From = this.ActualWidth,
To = newWidth
};
Storyboard.SetTarget(widthAnimation, this);
Storyboard.SetTargetProperty(widthAnimation, new PropertyPath(Window.WidthProperty));
storyboard.Children.Add(widthAnimation);
//---------------------------------------------------
// Animate Width
//---------------------------------------------------
var heightAnimation = new DoubleAnimation()
{
Duration = new Duration(duration),
From = this.ActualHeight,
To = newHeight
};
Storyboard.SetTarget(heightAnimation, this);
Storyboard.SetTargetProperty(heightAnimation, new PropertyPath(Window.HeightProperty));
storyboard.Children.Add(heightAnimation);
//---------------------------------------------------
// Play
//---------------------------------------------------
//storyboard.Begin();
this.BeginStoryboard(storyboard, HandoffBehavior.SnapshotAndReplace, false);
}), null);
}
BTW, I've created a generic version of this method for animating the sizes of my menus etc and it works perfectly. It seems to be only a problem with the Window animation. Does anyone knows how to fix it and apply animation for both window width and height? I followed after answers in SO but all of them related to elements other then Window.