프로젝트

일반

사용자정보

통계
| 브랜치(Branch): | 개정판:

markus / KCOM / Common / ImageAsyncHelper.cs @ 6a19b48d

이력 | 보기 | 이력해설 | 다운로드 (2.11 KB)

1
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
using System.Windows.Controls;
9
using System.Windows.Data;
10
using System.Windows.Media.Imaging;
11

    
12
namespace KCOM.Common
13
{
14
    public class LazyImage : DependencyObject
15
    {
16
        public static readonly DependencyProperty SourceProperty = DependencyProperty.Register("Source", typeof(string), typeof(LazyImage), new PropertyMetadata(null, OnSourcePropertyChanged));
17

    
18
        private static async void OnSourcePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
19
        {
20
            Image imageControl = d as Image;
21
            string imagePath = e.NewValue as string;
22

    
23
            if (imageControl != null && imagePath != null && !string.IsNullOrEmpty(imagePath))
24
            {
25
                if (imageControl.IsLoaded && imageControl.ActualWidth > 0 && imageControl.ActualHeight > 0)
26
                {
27
                    await LoadImageAsync(imagePath, imageControl);
28
                }
29
                else
30
                {
31
                    RoutedEventHandler onImageControlLoaded = null;
32
                    onImageControlLoaded = async (sender, args) =>
33
                    {
34
                        imageControl.Loaded -= onImageControlLoaded;
35
                        await LoadImageAsync(imagePath, imageControl);
36
                    };
37
                    imageControl.Loaded += onImageControlLoaded;
38
                }
39
            }
40
        }
41

    
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
    }
62
}
클립보드 이미지 추가 (최대 크기: 500 MB)