Click here to Skip to main content
11,478,619 members (67,427 online)
Click here to Skip to main content
Add your own
alternative version

WPF Modal Dialog

, 17 Mar 2013 LGPL3 148.8K 6.6K 84
How to set up a modal (blocking) dialog inside a WPF window.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using System.Windows.Threading;

namespace Technewlogic.Samples.WpfModalDialog
	/// <summary>
	/// Interaction logic for ModalDialog.xaml
	/// </summary>
	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;

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.


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

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