markus / KCOM / Common / ImageAsyncHelper.cs @ c4a8d205
이력 | 보기 | 이력해설 | 다운로드 (2.11 KB)
1 | c5519c44 | taeseongkim | using System; |
---|---|---|---|
2 | using System.Collections.Generic; |
||
3 | using System.Linq; |
||
4 | using System.Net; |
||
5 | using System.Text; |
||
6 | using System.Threading.Tasks; |
||
7 | using System.Windows; |
||
8 | 6a19b48d | taeseongkim | using System.Windows.Controls; |
9 | c5519c44 | taeseongkim | using System.Windows.Data; |
10 | 6a19b48d | taeseongkim | using System.Windows.Media.Imaging; |
11 | c5519c44 | taeseongkim | |
12 | namespace KCOM.Common |
||
13 | { |
||
14 | 6a19b48d | taeseongkim | public class LazyImage : DependencyObject |
15 | c5519c44 | taeseongkim | { |
16 | 6a19b48d | taeseongkim | public static readonly DependencyProperty SourceProperty = DependencyProperty.Register("Source", typeof(string), typeof(LazyImage), new PropertyMetadata(null, OnSourcePropertyChanged)); |
17 | c5519c44 | taeseongkim | |
18 | 6a19b48d | taeseongkim | private static async void OnSourcePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) |
19 | c5519c44 | taeseongkim | { |
20 | 6a19b48d | taeseongkim | Image imageControl = d as Image; |
21 | string imagePath = e.NewValue as string; |
||
22 | c5519c44 | taeseongkim | |
23 | 6a19b48d | taeseongkim | if (imageControl != null && imagePath != null && !string.IsNullOrEmpty(imagePath)) |
24 | c5519c44 | taeseongkim | { |
25 | 6a19b48d | taeseongkim | if (imageControl.IsLoaded && imageControl.ActualWidth > 0 && imageControl.ActualHeight > 0) |
26 | c5519c44 | taeseongkim | { |
27 | 6a19b48d | taeseongkim | await LoadImageAsync(imagePath, imageControl); |
28 | c5519c44 | taeseongkim | } |
29 | 6a19b48d | taeseongkim | else |
30 | c5519c44 | taeseongkim | { |
31 | 6a19b48d | taeseongkim | RoutedEventHandler onImageControlLoaded = null; |
32 | onImageControlLoaded = async (sender, args) => |
||
33 | { |
||
34 | imageControl.Loaded -= onImageControlLoaded; |
||
35 | await LoadImageAsync(imagePath, imageControl); |
||
36 | }; |
||
37 | imageControl.Loaded += onImageControlLoaded; |
||
38 | c5519c44 | taeseongkim | } |
39 | } |
||
40 | } |
||
41 | 6a19b48d | taeseongkim | |
42 | public string Source |
||
43 | { |
||
44 | get { return (string)GetValue(SourceProperty); } |
||
45 | set { SetValue(SourceProperty, value); } |
||
46 | } |
||
47 | |||
48 | private static async Task LoadImageAsync(string path, Image imageControl) |
||
49 | { |
||
50 | BitmapImage image = new BitmapImage(); |
||
51 | image.BeginInit(); |
||
52 | image.UriSource = new Uri(path); |
||
53 | image.CacheOption = BitmapCacheOption.OnLoad; |
||
54 | image.EndInit(); |
||
55 | |||
56 | await image.Dispatcher.BeginInvoke(new Action(() => |
||
57 | { |
||
58 | imageControl.Source = image; |
||
59 | })); |
||
60 | } |
||
61 | c5519c44 | taeseongkim | } |
62 | } |