Coding: WPF Dialog behind Main Window

I came across a problem today that a dialog window appears (or better: hides) behind the main window in a Windows Presentation Foundation (WPF) application.

Consider the following C# code:

var mainWindow = new MainWindow();
mainWindow.Show();

var dialog = new DialogWindow();
dialog.ShowDialog();

Window.ShowDialog() deactivates the message loop of the main window so that only the dialog box can be used. However, if you forget to set the owner of the dialog box, the dialog window behind the main window may disappear.

dialog.Owner = mainWindow;

does the trick.