在WPF中,是没有类似winform的OpenFileDialog控件的,那么要怎么办呢?
在wpf界面上,放置一个button按钮,双击生成点击事件,编写以下代码即可:
/// <summary>
/// 浏览选择文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BrowseButton_Click(object sender, RoutedEventArgs e)
{
string path = string.Empty;
Microsoft.Win32.OpenFileDialog openFileDlg = new Microsoft.Win32.OpenFileDialog();
// 过滤文件扩展名,设置接受的扩展名
openFileDlg.DefaultExt = ".exe";
openFileDlg.Filter = "可执行程序 (.exe)|*.exe";
// 设置初始目录
openFileDlg.InitialDirectory = this._path;
允许多选
//openFileDlg.Multiselect = true;
//openFileDlg.Filter = "All files (*.*)|*.*";
// 调用ShowDialog方法显示对话框
Nullable<bool> result = openFileDlg.ShowDialog();
// 显示名称
if (result == true)
{
path = openFileDlg.FileName;
FilePathTextBox.Text = path;
}
}
如果您要选择文件夹,可以使用:
/// <summary>
/// 浏览选择文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BrowseButton_Click(object sender, RoutedEventArgs e)
{
string path = string.Empty;
var dialog = new FolderBrowserDialog();
DialogResult result = dialog.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
{
path = dialog.SelectedPath;
FilePathTextBox.Text = path;
}
}
祝您用餐愉快。