The question's example code was about animating the Window.Left
property and I was looking for exact that case, but the given answer does work for an one-time use-case only.
Specifically: If the animation has been performed and the Window is then moved manually via drag&drop, the same animation procedure will not work again as desired. The animation will always use the end-coordinates of the recent animation run.
So if you moved the window, it will jump back before starting the new animation:
https://i.stack.imgur.com/tw33H.jpg
To solve that issue, it is required to remove any AnimationClock
from the animated property after the animation is completed.
That is done by using ApplyAnimationClock
or BeginAnimation
with null
as the second parameter:
public partial class MainWindow : Window
{
// [...]
private void ButtonMove_Click(object sender, RoutedEventArgs e)
{
AnimateWindowLeft(500, TimeSpan.FromSeconds(1));
}
private void AnimateWindowLeft(double newLeft, TimeSpan duration)
{
DoubleAnimation animation = new DoubleAnimation(newLeft, duration);
myWindow.Completed += AnimateLeft_Completed;
myWindow.BeginAnimation(Window.LeftProperty, animation);
}
private void AnimateLeft_Completed(object sender, EventArgs e)
{
myWindow.BeginAnimation(Window.LeftProperty, null);
// or
// myWindow.ApplyAnimationClock(Window.LeftProperty, null);
}
}
XAML:
<Window x:Class="WpfAppAnimatedWindowMove.MainWindow"
// [...]
Name="myWindow">
Result:
https://i.stack.imgur.com/T0DIA.jpg
See also Remarks section of Microsoft Docs - HandoffBehavior Enum