WPF 中使用 OpenFIleDialog
WPF 中好像没有 OpenFileDialog 的控件,只能借用其他的了。 SaveFileDialog 应该也是类似的。
▲ 测试界面
<Grid>
<StackPanel Orientation="Vertical" >
<TextBox Height="50" Margin="10" BorderThickness="1" VerticalContentAlignment="Center" BorderBrush="Black" x:Name="FileNameTextBox"/>
<Button x:Name="btnFileDialog" Click="BtnFileDialog_Click" Content="OpenFileDialog-win32" FontSize="20" FontWeight="Bold" Margin="10"/>
<Button x:Name="btnFileDialog1" Click="BtnFileDialog1_Click" Content="OpenFileDialog-winform" FontSize="20" FontWeight="Bold" Margin="10"/>
<Button x:Name="btnFileDialog2" Click="BtnFileDialog2_Click" Content="OpenFileDialog-winform" FontSize="20" FontWeight="Bold" Margin="10"/>
</StackPanel>
</Grid>
直接在 button 的 click 事件中写个测试。
用 win32 控件中的 OpenFileDialog
// 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;
}
用 Winform 中的 OpenFileDialog
项目中需要引用一下 System.Windows.Forms
。
System.Windows.Forms.OpenFileDialog openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
openFileDialog1.InitialDirectory = @"C:\Users\Administrator\Desktop\";
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
//此处做你想做的事 ...
FileNameTextBox.Text = openFileDialog1.FileName; ;
}
类似的还有 FolderBrowserDialog 文件夹浏览对话框;
System.Windows.Forms.FolderBrowserDialog folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog();
System.Windows.Forms.DialogResult result = folderBrowserDialog.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
{
FileNameTextBox.Text = folderBrowserDialog.SelectedPath;
}
至于 WPF 当然可以自己去实现一个,满足自己的定制需求。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了