WPF - Dialog Box


All standalone applications have a main window that exposes some functionality and displays some data over which the application operates through a GUI. An application may also display additional windows to do the following −

  • Display some specific information to users
  • Gather useful information from users
  • Both display and gather important information


Let’s take an example to understand the concept of Dialog Box. First of all, create a new WPF project with the name WPFDialog.

  • Drag one button and one textbox from the Toolbox.

  • When the user clicks this button, it opens another dialog box with Yes, No, and Cancel buttons and displays a message “click any button” on it.

  • When a user clicks any of them, this dialog box gets closed and shows a textbox with the information of the button that was clicked.

  • Here is the XAML code to initialize a button and a textbox with some properties.

<Window x:Class = "WPFDialog.MainWindow" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" 
   Title = "MainWindow" Height = "350" Width = "604"> 
      <Button Height = "23" Margin = "100" Name = "ShowMessageBox"  
         VerticalAlignment = "Top" lick = "ShowMessageBox_Click">
            Show Message Box
      <TextBox Height = "23" HorizontalAlignment = "Left" Margin = "181,167,0,0"  
         Name = "textBox1" VerticalAlignment = "Top" Width = "120" />

Here is the C# code in which the button click event is implemented.

using System; 
using System.Windows; 
using System.Windows.Controls;  

namespace WPFDialog { 
   /// <summary> 
      /// Interaction logic for MainWindow.xaml 
   /// </summary> 
   public partial class MainWindow : Window {
      public MainWindow() { 
      private void ShowMessageBox_Click(object sender, RoutedEventArgs e) { 
         string msgtext = "Click any button"; 
         string txt = "My Title"; 
         MessageBoxButton button = MessageBoxButton.YesNoCancel; 
         MessageBoxResult result = MessageBox.Show(msgtext, txt, button); 
         switch (result) { 
            case MessageBoxResult.Yes:textBox1.Text = "Yes"; 
            case MessageBoxResult.No:textBox1.Text = "No"; 
            case MessageBoxResult.Cancel:textBox1.Text = "Cancel"; 

When you compile and execute the above code, it will produce the following window.

Output of the Dialogbox

When you click on the button, it displays another dialog box (as shown below) that prompts the user to click a button.

Prompts the user to click

In case the user clicks the Yes button, it updates the textbox with the button content.

clicks the button