Microsoft MVP성태의 닷넷 이야기
WPF에서 로딩중 이미지를 구현 - Source [링크 복사], [링크+제목 복사]
조회: 8885
글쓴 사람
우코아
홈페이지
첨부 파일
 

안녕하세요.
소스코드를 간략하게 추려서 추가로 질문 드립니다.

원하는 것은 이미지가 로딩중에 GIF 이미지를 띄워서 '로딩중..'으로 표현하는 것입니다.
구글링을 뒤져가며 더듬더듬 따라해본 방법은 BackgroundWorker, UI쓰레드, 비동기(Async/Await)등을 해보았습니다.
많은 가르침 부탁 드립니다!


# MainWindow.xaml.cs

namespace WpfApp1
{
    /// <summary>
    /// MainWindow.xaml에 대한 상호 작용 논리
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            // GIF 이미지를 표현한 Window
            LoadingProcess loadingProcess;
            loadingProcess = new LoadingProcess();
            loadingProcess.Top = this.Top + (this.ActualHeight - loadingProcess.Height) / 2;
            loadingProcess.Left = this.Left + (this.ActualWidth - loadingProcess.Width) / 2;
            loadingProcess.Show();

            //이미지 로딩 호출
            ImageLoading();
        }

        private void ImageLoading()
        {
            this.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                (ThreadStart)delegate ()
                {
                    int imageWidth = 88;
                    WrapPanel_Images.Children.Clear();
                    DirectoryInfo di = new DirectoryInfo(@"C:\Users\dp\Desktop\TEST");
                    String fileFilters = "*.jpg|*.jpeg|*.png|*.gif|*.tiff|*.bmp";
                    String[] files = fileFilters.Split('|').SelectMany(searchPattern => Directory.GetFiles(@"C:\Users\dp\Desktop\TEST", searchPattern)).ToArray();

                    for (int i = 0; i < files.Length; i++)
                    {
                        BitmapImage bitmapImage = new BitmapImage();
                        bitmapImage.BeginInit();
                        bitmapImage.UriSource = new Uri(@files[i], UriKind.Absolute);
                        bitmapImage.DecodePixelWidth = 10;
                        bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                        bitmapImage.EndInit();

                        Image image = new Image();
                        image.Stretch = Stretch.Uniform;
                        image.Width = imageWidth;
                        image.Source = bitmapImage;


                        Border border = new Border();
                        border.BorderThickness = new Thickness(1);
                        border.BorderBrush = new SolidColorBrush(Color.FromRgb(41, 57, 86));
                        border.Margin = new Thickness(2, 2, 2, 2);
                        border.Width = imageWidth;
                        border.Height = imageWidth;
                        border.Child = image;

                        TextBlock imageName = new TextBlock();
                        imageName.Text = System.IO.Path.GetFileName(files[i]);
                        imageName.VerticalAlignment = VerticalAlignment.Center;
                        imageName.HorizontalAlignment = HorizontalAlignment.Center;
                        imageName.Margin = new Thickness(0, 0, 0, 10);
                        imageName.MaxWidth = imageWidth - 4;

                        DockPanel dockPanel = new DockPanel();
                        DockPanel.SetDock(border, Dock.Top);
                        DockPanel.SetDock(imageName, Dock.Bottom);
                        dockPanel.Children.Add(border);
                        dockPanel.Children.Add(imageName);

                        WrapPanel_Images.Children.Add(dockPanel);
                    }
                }
            );
        }
    }
}




# Main.Window.xaml
<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <DockPanel>
            <Grid DockPanel.Dock="Top">
                <Button Click="Button_Click" x:Name="button1">
                    Click
                </Button>
            </Grid>
            <Grid DockPanel.Dock="Bottom">
                <ScrollViewer HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Auto">
                    <WrapPanel x:Name="WrapPanel_Images" Orientation="Horizontal"/>
                </ScrollViewer>
            </Grid>
        </DockPanel>
    </Grid>
</Window>











[최초 등록일: ]
[최종 수정일: 1/4/2019]


비밀번호

댓글 작성자
 



2019-01-04 11시06분
소스 코드가 아니라, 프로젝트를 첨부해 주세요. 아래의 글을 참고하시고.

재현 가능한 최소한의 예제 프로젝트란?
; http://www.sysnet.pe.kr/2/0/11452

정성태

1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
5831이우람2/20/20233126ref 전역변수가 pinned가 될수 있나요? [2]
5830냉수마찰2/19/20233424C# GridView에 Column별 데이터 추가하는 방법에 대해 [1]
5829수박942/19/20233421키움 API를 윈폼과 WPF의 네임스페이스 없이 콘솔이나 WinUI3에서 사용할 수 있는 방법이 있나요? [2]파일 다운로드1
5828김재영2/19/20233207장기적으로는 this 구문을 안쓰는게 맞을까요? [2]
5827lee2/18/20233134파이썬 설치 오류 질문입니다 [1]
5826Syong2/14/20233705Socket 관련 Leak (OverlappedAsyncResult, OverlappedData) 관련 문의 [7]파일 다운로드1
5825박성원2/14/20233264Listview 컨트롤의 화면 전환 시 갱신 속도 [1]
5823검은콩2/13/20233871catch(Exception ex)의 line번호를 쉽게 알 수 없는지요? [7]
5822김지우2/11/20233141책을 보면서 sync, async 이해가 되지 않는 부분이 있습니다. [5]파일 다운로드2
5821검은콩2/9/20233147Async 신뢰성과 소켓데이터 [4]
5820차가워2/8/20233229다른 프로세스 실행 후 포커스 가져오기 [3]
5819취준생2/7/20233362WPF 관련 실무가 궁금합니다. [3]
5818윤길2/7/20232811ObservableCollection 에서 INotifyPropertyChanged 구현해야하나요? [2]
5817흰털너부리2/7/20232948배포 시 winform 실행 콘솔로그 보는 방법 [1]
5816흰털너부리2/6/20232761.net core json array validation 질문 드립니다. [1]
5815김재영2/6/20232884종단간 암호화에 대해 시나리오인데 타당한 시나리오일까요? [2]
5814한예지 donator2/6/20233236decompile? [9]
5813김재영2/5/20233119openssl genrsa 2048시 키 생성이 다르게 됩니다. - 파일첨부 [4]파일 다운로드1
5812김재영2/5/20233384openssl genrsa 2048시 키 생성이 다르게 됩니다. [2]
5811치르바2/3/20233214MiniDumpWriteDump API로 덤프수집을 했는데요.. [3]
5810이건우1/31/20233333윈도우서비스를 통한 웹통신관련 질문입니다 [3]
5809이상훈1/31/20233759다채널 영상 디스플레이어 개발 관련 질문입니다. [3]
5808근우1/30/20233438WPF 에서 UserControl 과 ControlTemplate 의 차이점은 무엇인가요? [6]
5807궁금맨1/28/20234592C# 10 책에 나온 예제의 결과가 제 컴에서는 좀 달라서요. 이유가 궁금합니다. [1]
5806스레드1/25/20233116총정리 - 다양한 스레드들 [초안] [1]파일 다운로드1
5805어웨이트1/25/20232983Taskcontinuewith vs Async/Await [2]파일 다운로드1
1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...