-
Notifications
You must be signed in to change notification settings - Fork 0
/
LazyLoadBehavior.cs
44 lines (38 loc) · 1.4 KB
/
LazyLoadBehavior.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
using System;
using System.ComponentModel;
using Microsoft.Maui.Controls;
using Microsoft.Maui.Controls.Internals;
namespace SafariBooksDownload
{
public class LazyLoadBehavior : Behavior<Image>
{
public static readonly BindableProperty SourceProperty =
BindableProperty.Create(nameof(Source), typeof(string), typeof(LazyLoadBehavior));
public string Source
{
get => (string)GetValue(SourceProperty);
set => SetValue(SourceProperty, value);
}
private Image _associatedImage;
protected override void OnAttachedTo(Image bindable)
{
base.OnAttachedTo(bindable);
_associatedImage = bindable;
bindable.PropertyChanged += OnImagePropertyChanged;
}
protected override void OnDetachingFrom(Image bindable)
{
base.OnDetachingFrom(bindable);
bindable.PropertyChanged -= OnImagePropertyChanged;
_associatedImage = null;
}
private async void OnImagePropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == VisualElement.IsVisibleProperty.PropertyName && _associatedImage.IsVisible)
{
// Load image asynchronously when the Image becomes visible
_associatedImage.Source = ImageSource.FromUri(new Uri(Source));
}
}
}
}