WPF 中使用 OpenFIleDialog

WPF 中好像没有 OpenFileDialog 的空间,只能借用其他的了。 SaveFileDialog 应该也是类似的。

▲ 测试界面

▲ 测试界面
1
2
3
4
5
6
7
8
<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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 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

1
2
3
4
5
6
7
8
9
10
11
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 文件夹浏览对话框;

1
2
3
4
5
6
7
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 当然可以自己去实现一个,满足自己的定制需求。

感谢支持!