WPF – Show Dialog with backdrop

dialog

Sometimes it handy to force the user’s attention to a specific screen. We can do this with a dialog, but sometimes the user doesn’t know that window is on top. To draw the user’s eye to the window, I like to place a backdrop between the rest of the application and the dialog window. I use the following code to make that happen.

   1: public bool? ShowDialogWithBackdrop(Window win)

   2: {

   3:     //create backgroup

   4:     Window backgroundWindow = new Window();

   5:     backgroundWindow.Top = 0;

   6:     backgroundWindow.Left = 0;

   7:     backgroundWindow.Height = SystemParameters.WorkArea.Height;

   8:     backgroundWindow.Width = SystemParameters.WorkArea.Width;

   9:     backgroundWindow.AllowsTransparency = true;

  10:     backgroundWindow.Background = Brushes.Transparent;

  11:     backgroundWindow.WindowStyle = WindowStyle.None;

  12:     backgroundWindow.ShowInTaskbar = false;

  13:     Rectangle rect = new Rectangle() { Fill = Brushes.Silver, Opacity = 0.5 };

  14:     backgroundWindow.Content = rect;

  15:     backgroundWindow.Show();

  16:     //set the owner so if the user clicks on the backdrop,

  17:     //the window will flash

  18:     win.Owner = backgroundWindow;

  19:     bool? rv = win.ShowDialog();

  20:     //dialog has returned. Close backdrop.

  21:     backgroundWindow.Close();

  22:     return rv;

  23: }