Click here to Skip to main content
12,820,523 members (29,247 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


89 bookmarked
Posted 17 May 2009

WPF Modal Dialog

, 17 Mar 2013 LGPL3
Rate this:
Please Sign up or sign in to vote.
How to set up a modal (blocking) dialog inside a WPF window.


There is a newer article with improved functionality here on CodeProject:


What can you do if you would like to display a modal / blocking dialog in WPF? By default, there is the possibility to use the Window.ShowDialog() method. This has the disadvantage that a completely new "Windows"-window will be created which is not part of our main application window (which again has several disadvantages that I don’t want to discuss here). I would like to present an alternative solution.

As shown in the image, we would like to have a half transparent overlay with some kind of content (here, just for example, we use a simple text message, but we could also display other controls).

The ModalDialog control

The functionality and design is outsourced in a User Control. The XAML of this control is quite simple: we have the half transparent border that we use as our overlay, the TextBlock to display our message, and two Buttons for OK / Cancel.

<Grid DataContext="{Binding ElementName=root}">
    <Border Background="#90000000" Visibility="{Binding Visibility}">
        <Border BorderBrush="Black" BorderThickness="1" Background="AliceBlue" 
                CornerRadius="10,0,10,0" VerticalAlignment="Center"
                <DropShadowBitmapEffect Color="Black" 
                  Opacity="0.5" Direction="270" 
                  ShadowDepth="0.7" />
            <Grid Margin="10">
                    <RowDefinition />
                    <RowDefinition Height="Auto" />
                <TextBlock x:Name="MessageTextBlock" 
                    Text="{Binding Message}" 
                    TextWrapping="Wrap" Margin="5" />
                <UniformGrid Grid.Row="1" Margin="5" 
                          Columns="2" HorizontalAlignment="Center"
                    <Button x:Name="OkButton" Click="OkButton_Click" 
                          Content="Ok" Margin="2"  />
                    <Button x:Name="CancelButton" 
                          Content="Cancel" Margin="2" />

Of course, it is still not clear how the "modal" or "blocking" behavior of the dialog is achieved. But how is that done? That’s a little bit tricky (you could also say "hacky" :-)). We have the following problem: "blocking" or "modal" means that the instruction pointer of our execution should remain at its position as long as the dialog is shown, and when the dialog is closed, it should continue. To achieve this, we would have to suspend the calling thread (typically the UI thread). If it is suspended, an interaction with our dialog will also be impossible because it is suspended, too. This is because WPF relies on a single thread model, which means it is impossible to run UI elements in another thread different from the thread of our main window. So we have to use a little hack here (I’m really not a friend of hacks, but here, it’s absolutely necessary).

When the dialog is shown, we start a loop in which we suspend the calling thread (typically the UI thread) for a short time, and we also advise the WPF dispatcher to process the messages (mouse click, movements, keystrokes, repaint, etc.) that occur in the sleeping time. If we choose a sleep time that is small enough, for the user it seems that the application is running fluently. Attention: If you would like to display elements in our dialog that have a lot of "animation" stuff on it, we will run into problems. If we just use some simple elements, it’s OK.

Here is the code for our control:

public partial class ModalDialog : UserControl
    public ModalDialog()
        Visibility = Visibility.Hidden;

    private bool _hideRequest = false;
    private bool _result = false;
    private UIElement _parent;

    public void SetParent(UIElement parent)
        _parent = parent;

    #region Message

    public string Message
        get { return (string)GetValue(MessageProperty); }
        set { SetValue(MessageProperty, value); }

    // Using a DependencyProperty as the backing store for Message.
    // This enables animation, styling, binding, etc...
    public static readonly DependencyProperty MessageProperty =
            "Message", typeof(string), typeof(ModalDialog), 
            new UIPropertyMetadata(string.Empty));


    public bool ShowHandlerDialog(string message)
        Message = message;
        Visibility = Visibility.Visible;

        _parent.IsEnabled = false;

        _hideRequest = false;
        while (!_hideRequest)
            // HACK: Stop the thread if the application is about to close
            if (this.Dispatcher.HasShutdownStarted ||

            // HACK: Simulate "DoEvents"
                new ThreadStart(delegate { }));

        return _result;
    private void HideHandlerDialog()
        _hideRequest = true;
        Visibility = Visibility.Hidden;
        _parent.IsEnabled = true;

    private void OkButton_Click(object sender, RoutedEventArgs e)
        _result = true;

    private void CancelButton_Click(object sender, RoutedEventArgs e)
        _result = false;

How to use the ModalDialog control

The dialog is used in the main application window, and as we can see, it overlays the complete content of the window:

    <Grid x:Name="ModalDialogParent">
        <StackPanel HorizontalAlignment="Left" VerticalAlignment="Top">
            <TextBox x:Name="MessageTextBox" 
              Text="Hello World!" Margin="3" />
            <Button x:Name="ShowModalDialog" 
              Content="Show Modal Dialog" Margin="3" />
            <TextBlock x:Name="ResultText" />

    <controls:ModalDialog x:Name="ModalDialog" />

Notice that the dialog needs a reference to the element that "holds" the complete content of the window. In our case, this is the grid with the name "ModalDialogParent". This is important so that the dialog can disable it when it is shown (otherwise, the user could cycle with "tab" through the elements of the window).

public partial class MainWindow : Window
    public MainWindow()

    private void ShowModalDialog_Click(object sender, RoutedEventArgs e)
        var res = ModalDialog.ShowHandlerDialog(MessageTextBox.Text);
        var resultMessagePrefix = "Result: ";
        if (res)
            ResultText.Text = resultMessagePrefix + "Ok";
            ResultText.Text = resultMessagePrefix + "Cancel";

Have fun!


This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)


About the Author

Ronald Schlenker
Software Developer (Senior)
Germany Germany
No Biography provided

You may also be interested in...

Comments and Discussions

GeneralRe: blocking method Pin
Philipp Sumi31-May-09 0:44
memberPhilipp Sumi31-May-09 0:44 
GeneralRe: blocking method Pin
Ronald Schlenker31-May-09 11:26
memberRonald Schlenker31-May-09 11:26 
GeneralRe: blocking method Pin
Philipp Sumi31-May-09 12:28
memberPhilipp Sumi31-May-09 12:28 
GeneralRe: blocking method Pin
Ronald Schlenker31-May-09 14:13
memberRonald Schlenker31-May-09 14:13 
You are not a pain, don't worry.

1) The solution you posted is definitely an alternative solution. That solution uses the ShowDialog() method which is basically doing this: It blocks the execution of the thread from which it was invoked. If the dialog is closed, the execution continues. Perfect! This is what I needed: It's a synchronous call to display a dialog.

2) I couldn't use ShowDialog because it is not possible to use a WPF control inside the main window, but only a completely new window as the dialog content. In my application, I needed the ability to host quite complex controls in the modal dialog which had to be in the main window so that they were arranged by the layout system.

3) The mentioned disadvantages refered to the posted _asynchronous_ solution, which means: you invoke the dialog, but you don't wait until it is closed. Instead, you continue the execution and a delegate is called when the dialog is closed. In most cases, this will fit the requirements - so use it! In my scenario, I had - unfortunately - problems with this pattern, because: To decouple our components, we implemented a small synchronous message/event bus. Components had the ability to react to certain messages, but the problem here was that if you needed user interaction, we had to block the execution of this message until the user made his decision. This cannot be achieved by using the asynchronous solution.

GeneralRe: blocking method Pin
Jürgen Bäurle22-Apr-11 10:41
memberJürgen Bäurle22-Apr-11 10:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170308.1 | Last Updated 18 Mar 2013
Article Copyright 2009 by Ronald Schlenker
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid