WPF 中使用 OpenFIleDialog
原创
©著作权归作者所有:来自51CTO博客作者覺醒的原创作品,请联系作者获取转载授权,否则将追究法律责任
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 当然可以自己去实现一个,满足自己的定制需求。