在WPF中中, OpenFileDialog位于 Microsoft.Win32 名称空间。WPF程序使用OpenFileDialog的方法如下:
(1)在Visual Studio中新建一个“WPF应用程序”项目
(2)MainWindow.xaml
(3)MainWindow.cs
using System.Windowsnamespace WpfApplication1
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent()
}
private void Button_Click(object sender, RoutedEventArgs e)
{
// 在WPF中, OpenFileDialog位于Microsoft.Win32名称空间
Microsoft.Win32.OpenFileDialog dialog =
new Microsoft.Win32.OpenFileDialog()
dialog.Filter = "文本文件|*.txt"
if (dialog.ShowDialog() == true)
{
lblFileName.Content = dialog.FileName
}
}
}
}
(4)运行效果
选择文件并打开后
详见代码和注释:
System.Windows.Forms.OpenFileDialog openFile = new System.Windows.Forms.OpenFileDialog()openFile.CheckFileExists = true//检查文件是否存在
openFile.CheckPathExists = true//检查路径是否存在
openFile.Multiselect = true//是否允许多选,false表示单选
openFile.InitialDirectory = "C:\\"//设置打开时的默认路径,我这里设置为C盘根目录
string filter = "txt,doc"
filter = filter.TrimEnd(',')
if (filter.Equals(""))
{
filter = "*"
}
filter = filter.Replace(",", "*.")
filter = "*." + filter
openFile.Filter = "Txt files (" + filter + ")|" + filter + "|All files (*.*)|*.*"//这里设置的是文件过滤器,比如选了txt文件,那别的文件就看不到了
if (openFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)//打开文件选择器,并按下选择按钮
{
String[] names = openFile.FileNames
String message = "已选择的文件如下:\r\n"
for (int i = 0 i < names.length i++)
{
message += names + "\r\n"
}
MessageBox.show(message)
}
另外,你说不能多选,这个多选时要按住Ctrl才能选中多个文件,或者按住鼠标左键滑动以选定多个目标才行。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)