TIP: Make a WPF dialog/window as application modal






4.85/5 (15 votes)
Generic tip to make a WPF window modal to the application's main window
When you create a new window from inside your application, like in this example:
if you press Alt-tab when the dialog is open, and you come back to the application pressing Alt-tab again, the main window will be shown but not the dialog. The reason is that the dialog has not been declared as owned by the main window.
The solution for this undesired behaviour is very simple: Inside the dialog constructor, right after the invocation to InitializeComponent(), set the owner of the dialog, which is the main window:
Where
var dialog = new MyDialog(); if (dialog.ShowDialog().Equals(true)) { // do something here }
if you press Alt-tab when the dialog is open, and you come back to the application pressing Alt-tab again, the main window will be shown but not the dialog. The reason is that the dialog has not been declared as owned by the main window.
The solution for this undesired behaviour is very simple: Inside the dialog constructor, right after the invocation to InitializeComponent(), set the owner of the dialog, which is the main window:
public MyDialog() { InitializeComponent(); this.Owner = App.Current.MainWindow; // Any other stuff you want to put here }
Where
App
is traditionally the name of the WPF application class.