ImageAttach.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. using System.Windows;
  2. using System.Windows.Controls;
  3. using System.Windows.Media;
  4. namespace HandyControl.Controls;
  5. public class ImageAttach
  6. {
  7. public static readonly DependencyProperty SourceFailedProperty = DependencyProperty.RegisterAttached(
  8. "SourceFailed", typeof(ImageSource), typeof(ImageAttach), new FrameworkPropertyMetadata(default(ImageSource), FrameworkPropertyMetadataOptions.Inherits, OnSourceFailedChanged));
  9. private static void OnSourceFailedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  10. {
  11. if (d is Image image)
  12. {
  13. if (e.NewValue is ImageSource)
  14. {
  15. image.ImageFailed += Image_ImageFailed;
  16. }
  17. else
  18. {
  19. image.ImageFailed -= Image_ImageFailed;
  20. }
  21. }
  22. }
  23. private static void Image_ImageFailed(object sender, ExceptionRoutedEventArgs e)
  24. {
  25. if (sender is Image image)
  26. {
  27. image.SetCurrentValue(Image.SourceProperty, GetSourceFailed(image));
  28. image.ImageFailed -= Image_ImageFailed;
  29. }
  30. }
  31. public static void SetSourceFailed(DependencyObject element, ImageSource value)
  32. => element.SetValue(SourceFailedProperty, value);
  33. public static ImageSource GetSourceFailed(DependencyObject element)
  34. => (ImageSource) element.GetValue(SourceFailedProperty);
  35. }