Creating Storyboard in code behind in WPF

后端 未结 3 1205
忘掉有多难
忘掉有多难 2020-12-05 09:57

The following code is working fine.


    
        
                   


        
3条回答
  •  北荒
    北荒 (楼主)
    2020-12-05 10:47

    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://imgur.com/a/hxRCqm7

    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:

    
    

    Result:
    https://imgur.com/a/OZEsP6t

    See also Remarks section of Microsoft Docs - HandoffBehavior Enum

提交回复
热议问题