Tuesday, December 20, 2011

Showing a modal and continue to execution of calling window

Again some bits of code. For a couple of reason you may consider not using the ShowDialog method of a window, one is that the calling method does not continue the execution and it blocks until the dialog window becomes closed. I have written my MVVM tool set in a way that this behaviour causes some problems. The other reason is ShowDialog blocks all other windows in your application, so what if you want to open a window over another window in a way that only the calling window becomes blocked. Here is the solution I came up with:

public static class WPFWindowExtensions
{
    public static void ShowNonBlockingModal(this Window window)
    {
        var parent = window.Owner;
        EventHandler parentDeactivate = (_, __) => { window.Activate(); };
        parent.Activated += parentDeactivate;
        EventHandler window_Closed = (_, __) => { parent.Activated -= parentDeactivate; };
        window.Show();
    }
}

I tried to keep it simple to be more readable, however you may add a check for the window.Owner to have a value and throw an exception if it is null, or you may automatically set the owner with the current active window as described in this blog post.


1 comment:

  1. I needed a modal window that let execution continue after it was opened, and this worked perfect right out of the box! Thanks!

    ReplyDelete