Wednesday, 7 May 2014

WPF - How to use FileOpenDialog, SaveFileDialog, PrintDialog

Unlike in Windows Forms, WPF doesn't have a FileOpenDialog component in the Controls toolkit.
But you can access the Dialogs classes from Microsoft.Win32 namespace.
A sample usage is as below:
// Configure open file dialog box
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".txt"; // Default file extension
dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension

// Show open file dialog box
Nullable<bool> result = dlg.ShowDialog();

// Process open file dialog box results
if (result == true)
// Open document
string filename = dlg.FileName;

Similarly you can use other DialogBoxes from the namespace like:
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
System.Windows.Controls.PrintDialog dlg = new System.Windows.Controls.PrintDialog();

No comments:

Post a Comment