gracexu

  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按钮可以浏览文件。

分类:

技术点:

相关文章:

  • 2021-05-25
  • 2020-04-26
  • 2021-08-29
  • 2021-08-11
  • 2021-11-07
  • 2021-10-22
  • 2021-06-29
  • 2021-09-03
猜你喜欢
  • 2021-08-29
  • 2021-12-24
  • 2019-12-03
  • 2021-09-26
  • 2021-11-04
  • 2021-12-31
相关资源
相似解决方案