WPF中的OpenFileDialog

WPF开发过程中,也有打开指定文件或者是导入文件的需求,事实上WPF中并未提供专门的负责进行文件打开的对话框类。因此通常需要引用非WPF的对话框类来完成此功能。有两种办法,一种是利用Microsoft.Win32.OpenFileDialog,另一种是System.Windows.Forms.OpenFileDialog,但是采用第二种的话需要添加对于相关类库的引用。通常采用第一种方式。

相关的代码如下:

            // Create OpenFileDialog 
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();



            // Set filter for file extension and default file extension 
            dlg.DefaultExt = ".png";
            dlg.Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif";


            // Display OpenFileDialog by calling ShowDialog method 
            Nullable result = dlg.ShowDialog();


            // Get the selected file name and display in a TextBox 
            if (result == true)
            {
                // Open document 
                string filename = dlg.FileName;
            }

你可能感兴趣的:(WPF)