WPF中实现文件夹对话框(OpenFileDialog in WPF)
OpenFileDialog控件在WinForm中经常用来浏览本机文件。OpenFileDialog类的命名空间是Microsoft.Win32.OpenFileDialog,它不能作为WPF控件被直接使用。
实际上在WPF我们可以使用一个TextBox控件和Button控件来实现OpenFileDialog的功能。
首先,我们在WPF项目XAML页拖一个TextBox控件和Button控件,如下图所示:
xaml文件中将出现这样的代码:
<TextBox Height="32" HorizontalAlignment="Left" Margin="6,10,0,0" Name="FileNameTextBox" VerticalAlignment="Top" Width="393" /> <Button Content="Browse" Height="32" HorizontalAlignment="Left" Margin="405,10,0,0" Name="button1" VerticalAlignment="Top" Width="88" Click="button1_Click" />
然后,在button Click事件中添加如下代码。
// Create OpenFileDialog Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); // Set filter for file extension and default file extension dlg.DefaultExt = ".txt"; dlg.Filter = "Text documents (.txt)|*.txt"; // Display OpenFileDialog by calling ShowDialog method Nullable<bool> result = dlg.ShowDialog(); // Get the selected file name and display in a TextBox if (result == true) { // Open document string filename = dlg.FileName; FileNameTextBox.Text = filename; }
这样就完成了。点击Browse按钮可以浏览文件。