WPF ShowDialog returns immediately

Sometimes, when I call ShowDialog in the OpenFileDialog Window in WPF, the dialog closes immediately with a false value returned.

I call ShowDialog in response to a button click event. I can reproduce this problem using the sample code for OpenFileDialog on MSDN:

// 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;
}

The problem occurs intermittently when I run my solution in debug mode from Visual Studio 2008 SP1. This is pretty annoying.

Is this a known issue? Are there any workarounds?

+3
source share
1 answer

The problem is that OpenFileDialog requires a window to attach. If the window is missing, it immediately returns with the result "false".

:

var ofd = new OpenFileDialog();
ofd.ShowDialog(Application.Current.MainWindow);

http://www.wpftutorial.net

+2

Source: https://habr.com/ru/post/1744961/


All Articles