Search code examples
wpfshowdialog

ShowDialog() behind the parent window


I am using ShowDialog() with WindowStyle = WindowStyle.SingleBorderWindow; to open a modal window in my WPF (MVVM) application, but it lets me navigate to parent window using the Windows taskbar (Windows 7).

I've found an answer here: WPF and ShowDialog() but it isn't suitable for me because I don't need an "always on top" tool window.

Thanks in advance


Solution

  • 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
        }
    }