Search code examples
wpfwpf-animation

How to correctly stop a storyboard declared programmatically


I've a WPF application that performs a cell blink when a value in the datasource has been updated and it works fine.

I've noticed profiling the application that when I perform the update really fast the memory is growing. Since I start the storyboard in this way

 private static DoubleAnimation blink =
        new DoubleAnimation()
        {
            From = 0,
            To = 1,
            Duration = TimeSpan.FromSeconds(0.2),
            FillBehavior = FillBehavior.Stop
        };
 private void Items_ItemChanged(object sender, ItemChangedEventArgs<ExpandoObject> e)
    {
       var club = e.Item;
       var row = grid.ItemContainerGenerator.ContainerFromItem(club) as Telerik.Windows.Controls.GridView.GridViewRow;
       if (row != null)
       {
          var column = grid.Columns[e.PropertyName];
          var cell = row.Cells.FirstOrDefault(c => c.Column == column);
          if (cell != null)   //In case of virtualization I won't have all the columns
          {
              Storyboard.SetTarget(blink, cell.Content as TextBlock);
              Storyboard.SetTargetProperty(blink, new PropertyPath(Button.OpacityProperty));
              var sb = new Storyboard();
              sb.Children.Add(blink);
              sb.Begin();
          }
       }
    }

I suspect I've to stop the animation but I don't know how I 've to do it?

Thanks


Solution

  • Take out Storyboard from Items_ItemChanged.

        Storyboard sb = new Storyboard();
        private void Items_ItemChanged(object sender, ItemChangedEventArgs<ExpandoObject> e)
        {
            sb.Stop();
            sb.Children.Clear();
    
            sb.Children.Add(blink);
    
            var club = e.Item;
            var row = grid.ItemContainerGenerator.ContainerFromItem(club) as Telerik.Windows.Controls.GridView.GridViewRow;
            if (row != null)
            {
                var column = grid.Columns[e.PropertyName];
                var cell = row.Cells.FirstOrDefault(c => c.Column == column);
                if (cell != null)   //In case of virtualization I won't have all the columns
                {
                    Storyboard.SetTarget(blink, cell.Content as TextBlock);
                    Storyboard.SetTargetProperty(blink, new PropertyPath(Button.OpacityProperty));
    
                    sb.Begin();
                }
            }
        }