none
How to stop animation in WPF? RRS feed

  • Question

  • Question: How to stop animation in WPF at any given moment?

    Note: Animation is done using the DoubleAnimation and Storyboard classes.

    Code:

        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
    
                this.Loaded += MainWindow_Loaded;
            }
    
            Line line;
    
            void MainWindow_Loaded(object sender, RoutedEventArgs e)
            {
                Canvas canvas = new Canvas();
                canvas.Background = Brushes.Black;
                this.Content = canvas;
    
                line = new Line();
                line.Stroke = Brushes.White;
                line.X1 = 0;
                line.Y1 = 0;
                line.X2 = 100;
                line.Y2 = 100;
    
                canvas.Children.Add(line);
    
                Animation();
            }
    
            private void Animation()
            {
                DoubleAnimation DB = new DoubleAnimation();
                DB.By = 100;
                DB.AutoReverse = true;
                DB.RepeatBehavior = RepeatBehavior.Forever;
                DB.Duration = new Duration(TimeSpan.FromMilliseconds(100));
    
                string name = "line";
                RegisterName(name, line);
    
                Storyboard SB = new Storyboard();
                Storyboard.SetTargetName(DB, name);
                Storyboard.SetTargetProperty(DB, new PropertyPath(Line.X2Property));
                SB.Children.Add(DB);
    
                SB.Begin(this, true);
    
                this.MouseDown += delegate
                {
                    SB.Stop(); // Does not stop.
                };
            }
        }
    Tuesday, September 1, 2015 9:44 AM

Answers

All replies