2010년 2월 21일 일요일

WPF OpenFileDialog

원문 : WPF OpenFileDialog





WPF OpenFileDialog



WPF 에서 OpenFileDialog 를 이용하는 방법을 알아보자. 파일을 여는 대화상자는 Windows 프로그램에서 워낙 일반적이고 자주 사용되기 때문에 언어적 차원에서 미리 구현되어 있어 사용하기만 하면 됬다. WinForm 에서도 OpenFileDialog 가 존재하는데 내부적으로는 Win32 API 를 이용한다. 그렇다면 WPF 에서는??

테스트할 WPF 데모 프로젝트를 만들자.

우선 xaml 파일에 테스트할 응용프로그램을 아래와 같이 디자인 한다.

<Grid>        <Button Content="Browse" Height="32" HorizontalAlignment="Left"
                Margin="20,12,0,0" Click="button1_Click"                Name="button1" VerticalAlignment="Top" Width
="136" />
        <Image Margin="12,70,0,20" Name="MyImage" Stretch="Fill" HorizontalAlignment="Left" Width="200" />        <ListBox Margin="263,70,46,20" Name="listBox1" /></Grid>




버튼 클릭 이벤트 핸들러를 다음과 같이 코딩해 준다.

private void button1_Click(object sender, RoutedEventArgs e)
        {
            Stream checkStream = null;
            Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();

            openFileDialog.Multiselect = false;
            //
openFileDialog.InitialDirectory = "c:\\";            //if you want filter only .txt file            //dlg.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            //if you want filter all files                        openFileDialog.Filter = "All Image Files | *.*";
            if ((bool)openFileDialog.ShowDialog())
            {
               
try                {
                    if ((checkStream = openFileDialog.OpenFile()) != null)
                    {
                       MyImage.Source = new BitmapImage(new Uri(openFileDialog.FileName, UriKind.Absolute));
                        listBox1.Items.Add(openFileDialog.FileName);
                        MessageBox.Show("Successfully done");
                    }
                }
                 catch (Exception ex)
                {
                        MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
           
else            {
                MessageBox.Show("Problem occured, try again later");
             }        }



cfile29.uf.1168363350AEC2F81E507C.zip

위 코드에서 알 수 있듯이 WPF 의 OpenFileDailog 역시 내부적으로는 Win32 API 를 사용한다.
OpenFileDialog 클래스의 사용 방법은 C++, WinForm 과 특별히 다르지 않다.



댓글 없음:

댓글 쓰기