1、选择对话框

部分:

  1. // 在WPF中,OpenFileDialog位于Microsoft.Win32名称空间
  2. Microsoft.Win32.OpenFileDialog dialog =
  3. new Microsoft.Win32.OpenFileDialog();
  4. dialog.Filter = "文本文件|*.txt";
  5. if (dialog.ShowDialog() == true)
  6. {
  7. lblFileName.Content = dialog.FileName;
  8. }

完整:

  1. public string SelectFileWpf()
  2. {
  3. var openFileDialog = new Microsoft.Win32.OpenFileDialog()
  4. {
  5. Filter = "Text documents (.txt)|*.txt|All files (*.*)|*.*"
  6. };
  7. var result = openFileDialog.ShowDialog();
  8. if (result == true)
  9. {
  10. return openFileDialog.FileName;
  11. }
  12. else
  13. {
  14. return null;
  15. }
  16. }

WPF选择文件、文件夹和另存为对话框 - 图1



2、选择文件夹对话框

  • a、添加 System.Windows.Forms 的引用

WPF选择文件、文件夹和另存为对话框 - 图2
WPF选择文件、文件夹和另存为对话框 - 图3
b、引用命名空间,为避免类名冲突可以给命名空间别名

  1. using WinForm = System.Windows.Forms;

c、使用 System.Windows.Forms 命名空间下的 FolderBrowserDialog 类

  1. WinForm.FolderBrowserDialog dialog = new WinForm.FolderBrowserDialog();
  2. dialog.ShowDialog();

效果如下:
WPF选择文件、文件夹和另存为对话框 - 图4


  • a、打开程序包管理器控制台

WPF选择文件、文件夹和另存为对话框 - 图5
b、安装WindowsAPICodePack-Shell包,使用Install-Package WindowsAPICodePack-Shell命令。
注意对应的项目

WPF选择文件、文件夹和另存为对话框 - 图6
c、使用CommonOpenFileDialog类打开对话框

  1. CommonOpenFileDialog dialog = new CommonOpenFileDialog();
  2. dialog.IsFolderPicker = true;//设置为选择文件夹
  3. dialog.ShowDialog();

效果如下:

WPF选择文件、文件夹和另存为对话框 - 图7



3、另存为对话框

SaveFileDialog类位于PresentationFramework.dll 的Microsoft.Win32命名空间

  1. public static string ChooseSaveFile(string title,string initFolder)
  2. {
  3. SaveFileDialog dlg = new SaveFileDialog();
  4. dlg.Title = title;
  5. dlg.FileName = "User.txt"; // Default file name
  6. dlg.DefaultExt = ".txt"; // Default file extension
  7. dlg.Filter = "Text documents|*.txt"; // Filter files by extension
  8. dlg.InitialDirectory = initFolder;
  9. // Process save file dialog box results
  10. if (dlg.ShowDialog() == true)
  11. {
  12. return dlg.FileName;
  13. }
  14. else
  15. {
  16. return null;
  17. }
  18. }