private static void AnimatedSourceChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { Image imageControl = o as Image; if (imageControl == null) { return; } var oldValue = e.OldValue as ImageSource; var newValue = e.NewValue as ImageSource; if (ReferenceEquals(oldValue, newValue)) { if (imageControl.IsLoaded) { var isAnimLoaded = GetIsAnimationLoaded(imageControl); if (!isAnimLoaded) { InitAnimationOrImage(imageControl); } } return; } if (oldValue != null) { imageControl.Loaded -= ImageControlLoaded; imageControl.Unloaded -= ImageControlUnloaded; imageControl.IsVisibleChanged -= VisibilityChanged; AnimationCache.RemoveControlForSource(oldValue, imageControl); var controller = GetAnimationController(imageControl); if (controller != null) { controller.Dispose(); } imageControl.Source = null; } if (newValue != null) { imageControl.Loaded += ImageControlLoaded; imageControl.Unloaded += ImageControlUnloaded; imageControl.IsVisibleChanged += VisibilityChanged; if (imageControl.IsLoaded) { InitAnimationOrImage(imageControl); } } }
static void ImageControlUnloaded(object sender, RoutedEventArgs e) { Image imageControl = sender as Image; if (imageControl == null) { return; } var source = GetAnimatedSource(imageControl); if (source != null) { AnimationCache.RemoveControlForSource(source, imageControl); } var controller = GetAnimationController(imageControl); if (controller != null) { controller.Dispose(); } }