WPF程序中使用Vista/Win7风格的OpenFolderDialog
WPF中没有自带的用于选择打开文件夹的对话框控件,因此要在程序中使用OpenFolderDialog,主要有三种方法:
- 使用WinForm封装的系统对话框:System.Windows.Forms.FolderBrowserDialog;
- P/Invoke,调用Win32 API SHBrowseForFolder();
- 自己动手写一个
- 前两种本质上都是一样的,都是调用SHBrowseForFolder()打开老式的文件夹选择对话框:
这种老式的文件夹对话框有个缺点,就是指定默认文件夹位置后,无法导航到默认文件夹的上一级目录,导致用户只能选择默认文件夹及其子文件夹。
Windows Vista/Win7中出现了一种新式的文件和文件夹选择对话框:
这种新文件和文件夹选择对话框不仅外观漂亮,同时也更灵活,可以选择系统中的任意文件和文件夹。
要在WPF中使用这种新式的文件夹对话框,可以使用MS官方发布的Windows API code pack,其中有个类CommonOpenFileDialog,可以实现这一功能。
不过奇怪的是,无论从这个类的命名,以及官方文档来看,这个类似乎只有选择文件的功能,官方文档对这个类的描述是:
Creates a Vista or Windows 7 Common File Dialog, allowing the user to select one or more files.
但实际上,这个类是具备选择文件夹对话框功能的,只需要将IsFolderPicker属性设为true即可。
示例代码:
1: //Add reference from Windows API code pack :
2: // Microsoft.WindowsAPICodePack
3: // Microsoft.WindowsAPICodePack.Shell
4: //
5: //using Microsoft.WindowsAPICodePack.Dialogs;
6: var d = new CommonOpenFileDialog();
7: d.IsFolderPicker = true; //set to false if need to select files8: d.Title = "Select Thunder app folder:";
9: d.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);10: var result = d.ShowDialog();11: if (result == CommonFileDialogResult.OK)
12: {13: textboxThunderFolder.Text = d.FileName;14: }