ShowDialog() behind the parent window

I had this problem but as the Window was being opened from a view model I didn't have a reference to the current window. To get round it I used this code:

var myWindow = new MyWindowType();
myWindow.Owner = Application.Current.Windows.OfType<Window>().SingleOrDefault(x => x.IsActive);

You can use: myWindow.Owner = Application.Current.MainWindow;

However, this method causes problems if you have three windows open like this:

MainWindow
   |
   -----> ChildWindow1

               |
               ----->  ChildWindow2

Then setting ChildWindow2.Owner = Application.Current.MainWindow will set the owner of the window to be its grandparent window, not parent window.


Much of the reason for the MVVM pattern is so that your interaction logic can be unit tested. For this reason, you should never directly open a window from the ViewModel, or you'll have dialogs popping up in the middle of your unit tests.

Instead, you should raise an event that the View will handle and open a dialog for you. For example, see this article on Interaction Requests: https://msdn.microsoft.com/en-us/library/gg405494(v=pandp.40).aspx#sec12


When the parent window makes (and shows) the child window, that is where you need to set the owner.

public partial class MainWindow : Window
{

    private void openChild()
    {
        ChildWindow child = new ChildWindow ();
        child.Owner = this; // "this" is the parent
        child.ShowDialog();
    }
 }

Aditionally, if you don't want an extra taskbar for all the children... then

<Window x:Class="ChildWindow"           
        ShowInTaskbar="False" >
</Window>

Try setting the Owner property of the dialog. That should work.

Window dialog = new Window();
dialog.Owner = mainWindow;
dialog.ShowDialog();

Edit: I had a similar problem using this with MVVM. You can solve this by using delegates.

public class MainWindowViewModel
{
    public delegate void ShowDialogDelegate(string message);
    public ShowDialogDelegate ShowDialogCallback;

    public void Action()
    {
        // here you want to show the dialog
        ShowDialogDelegate callback = ShowDialogCallback;
        if(callback != null)
        {
            callback("Message");
        }
    }
}

public class MainWindow
{
    public MainWindow()
    {
        // initialize the ViewModel
        MainWindowViewModel viewModel = new MainWindowViewModel();
        viewModel.ShowDialogCallback += ShowDialog;
        DataContext = viewModel;
    }

    private void ShowDialog(string message)
    {
        // show the dialog
    }
}

Tags:

Wpf

Showdialog