Modal Controls Via DispatcherFrame

wpf dispatcherframe

Lets say your new WPF gui has a button that loads confidential data. Lets then say that during the button’s click handler you need to get some credentials from the user BEFORE continuing code execution within the handler. The usual approach would be to popup a modal window via Window.ShowDialog(), because the gui thread will block until the popup is closed (for getting credentials in this scenario) which is the desired behaviour.
But what if you wanted to do something a bit more complex, using controls in the existing logical tree ? You could have a hidden control with a high z-index that you can make visible (emulating a popup), but the gui won’t block at that point, because if it does you wont be able to interact with that control (its a deadlock).
The solution is to use a little-known feature of the WPF Dispatcher, called DispatcherFrame – with which you can create nested message pumps, that allow the user to interact with controls while the main Dispatcher thread is blocked.
Here’s some sample code to illustrate the approach

I don’t think there are many scenarios where this would be the best approach, but its a neat trick if you need to use it.

About the author

Dean Chalk

I am a freelance (contract) Microsoft WPF developer, specialising in challenging, high-performance user interface development. I have been working exclusively on enterprise WPF app development since 2006, and I have been a part of some of the most demanding WPF projects ever created withing the Investment Banking / trading industry.

  • stbauer says:

    Thanks for this – really works great!


  • >