Select 在 WPF 中归档并继续程序

Select File and Continue Program In WPF

我一直在尝试按照教程和各种 Stack Overflow 帖子等来实现 select 文件的 OpenFileDialog。问题是,我似乎无法让我的程序继续执行其余逻辑。不完全确定它是否与我试图在主 window 中打开文件对话框或什么有关。考虑以下片段:

public MainWindow()
       {
           InitializeComponent();
           string file = "";
           // Displays an OpenFileDialog so the user can select a file.  
           OpenFileDialog openFileDialog1 = new OpenFileDialog();
           openFileDialog1.Filter = "Files|*.txt;*.out";
           openFileDialog1.Title = "Select a File";
           openFileDialog1.ShowHelp = true;

           // Show the Dialog.  
           // If the user clicked OK in the dialog and  
           // a file was selected, open it.  
           if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
           {
               //file = openFileDialog1.FileName;
               //file = openFileDialog1.OpenFile().ToString();
               //openFileDialog1.Dispose();
           }
           openFileDialog1 = null;
           Console.WriteLine("File path is: " + file);

如您所见,我什至尝试在对话框完成之前将 "Help" 值设置为 true。我已经尝试 select 文件字符串的文件名等,但无济于事 - 程序似乎只是在文件从对话框中 selected 之后等待。这里有人有解决方案的建议吗?

OpenFileDialog.ShowDialog() 是一个 modal method:

FileDialog is a modal dialog box; therefore, when shown, it blocks the rest of the application until the user has chosen a file. When a dialog box is displayed modally, no input (keyboard or mouse click) can occur except to objects on the dialog box. The program must hide or close the dialog box (usually in response to some user action) before input to the calling program can occur.

这意味着调用此方法将阻塞您的主线程,直到对话框关闭。您有一些选择:

  • 在初始化主 window 后调用 FileDialog。
  • 调用文件对话框from a thread。这种情况,注意同步。

以前我在使用 WPF 时遇到过同样的问题。当您使用 WPF 时,System.Windows.Form 命名空间不包含在您的 Project references;

另一方面,实际上有两个 OpenFileDialog,第一个是 System.Windows.Forms.OpenFileDialog(这就是您所拥有的),第二个是 Microsoft.Win32.OpenFileDialog。如果你想让你的代码工作,你必须将 System.Windows.Forms 添加到你的引用中:

Solution Explorer -> YourProject -> References (右键单击并添加引用...) -> Assembly -> Framework -> Find And Select System.Windows.Forms -> 确定

下一个解决方案是使用Microsoft.Win32,这很简单。只需将此命名空间添加到您的代码文件中并像这样更改您的代码:

 string file = "";
 // Displays an OpenFileDialog so the user can select a file.  
 OpenFileDialog openFileDialog1 = new OpenFileDialog();
 openFileDialog1.Filter = "Files|*.txt;*.out";
 openFileDialog1.Title = "Select a File";

 // Show the Dialog.  
 // If the user clicked OK in the dialog and  
 // a file was selected, open it.  
 if (openFileDialog1.ShowDialog() == true)
 {
     file = openFileDialog1.FileName;
     //file = openFileDialog1.OpenFile().ToString();
     //openFileDialog1.Dispose();
 }
 openFileDialog1 = null;
 Console.WriteLine("File path is: " + file);