Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Arrow up icon
GO TO TOP
Windows Presentation Foundation Development Cookbook

You're reading from   Windows Presentation Foundation Development Cookbook 100 recipes to build rich desktop client applications on Windows

Arrow left icon
Product type Paperback
Published in Feb 2018
Publisher Packt
ISBN-13 9781788399807
Length 524 pages
Edition 1st Edition
Arrow right icon
Author (1):
Arrow left icon
Kunal Chowdhury Kunal Chowdhury
Author Profile Icon Kunal Chowdhury
Kunal Chowdhury
Arrow right icon
View More author details
Toc

Table of Contents (18) Chapters Close

Title Page
Copyright and Credits
Packt Upsell
Contributors
Preface
1. WPF Fundamentals FREE CHAPTER 2. Using WPF Standard Controls 3. Layouts and Panels 4. Working with Data Bindings 5. Using Custom Controls and User Controls 6. Using Styles, Templates, and Triggers 7. Using Resources and MVVM Patterns 8. Working with Animations 9. Using WCF Services 10. Debugging and Threading 11. Interoperability with Win32 and WinForm 1. Other Books You May Enjoy Index

Creating a dialog box


A dialog box is also a kind of window, and is generally used to get some inputs from the user or to show a message to the user. It uses a model window to prevent users from interacting with other windows of the same application when it is already open. In this recipe, we will learn how to create a model dialog and use the common dialog boxes that the framework provides.

Getting ready

To get started with building and using dialog boxes in a WPF application, open your Visual Studio IDE and create a new WPF project, calling it CH01.DialogBoxDemo.

How to do it...

Follow these steps to create the dialog window and invoke it from the MainWindow to show a message to the user:

  1. Open the Solution Explorer and right-click on the project node.
  2. From the context menu, select Add | Window... to open the Add New Item dialog.
  3. Making sure that the Window (WPF) template is selected, give it the name MessageDialog, and click Add to continue. This will create MessageDialog.xaml and MessageDialog.xaml.cs files in the project.
  4. Open the MessageDialog.xaml file and replace the entire XAML content with the following:
<Window x:Class="CH01.DialogBoxDemo.MessageDialog" 
 xmlns=
   "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    ShowInTaskbar="False" WindowStyle="SingleBorderWindow" 
    Title="Message" Height="150" Width="400"  
    FontSize="14" Topmost="True" ResizeMode="NoResize"> 
   
    <Grid> 
       <TextBlock TextWrapping="Wrap" Margin="8" 
        Text="Thank you for reading 'Windows Presentation 
        Foundation Cookbook'. Click 'OK' to continue next."/> 
        <StackPanel Orientation="Horizontal" 
                    VerticalAlignment="Bottom"  
                    HorizontalAlignment="Right" 
                    Margin="4"> 
            <Button Content="OK" Width="60" Height="30" 
                    Margin="4" IsDefault="True"  
                    Click="OnOKClicked"/> 
            <Button Content="Cancel" Width="60" Height="30" 
                    Margin="4" IsCancel="True"  
                    Click="OnCancelClicked"/> 
        </StackPanel> 
    </Grid> 
</Window>
  1. Open the MessageDialog.xaml.cs file, and add the following event implementations for the OK button and Cancel button:
private void OnOKClicked(object sender, RoutedEventArgs e) 
{ 
    DialogResult = true; 
} 
 
private void OnCancelClicked(object sender, RoutedEventArgs e) 
{ 
    DialogResult = false; 
} 
  1. Now open the MainWindow.xaml page and replace the Grid with the following XAML content:
<Grid> 
    <ListBox x:Name="result" Height="100" Margin="8" 
             HorizontalAlignment="Stretch"  
             VerticalAlignment="Top" /> 
    <Button Content="Show Message" Width="150" Height="30"  
            VerticalAlignment="Bottom" Margin="8" 
            Click="OnShowMessageButtonClicked"/> 
</Grid> 
  1. Go to the code-behind file, MainWindow.xaml.cs, and add the button event implementation as shared in the following code section:
private void OnShowMessageButtonClicked(object sender, RoutedEventArgs e) 
{ 
    var messageDialog = new MessageDialog(); 
    var dialogResult = messageDialog.ShowDialog(); 
 
    if (dialogResult == true) 
    { 
        result.Items.Add("You clicked 'OK' button."); 
    } 
    else if (dialogResult == false) 
    { 
        result.Items.Add("You clicked 'Cancel' button."); 
    } 
}
  1. Now run the application. The visible window will have a button labeled Show Message. Click on it to invoke the message dialog window that we have created:
  1. Click on the Cancel button, which will add You clicked 'Cancel' button text into the list present in the MainWindow.
  2. Launch the message window again and click on the OK button. This will add You clicked 'OK' button in the list.

How it works...

When you call the ShowDialog() method of the Window instance, it opens it as a model dialog and waits until the user provides an input to it. In this case, the user input is the interaction with the OK and Cancel button. When you click the OK button, the associated event handler assigns true to the DialogResult property and returns to the caller. Similarly, the Cancel button event handler, assigns false to the DialogResult property and returns.

Based on the return value of the ShowDialog() method, which actually returns the value of DialogResult, you can decide whether the user clicked the OK or Cancel button.

The dialog window has been customized by setting the following properties to the Window instance:

  • The ShowInTaskbar property has been set to False to prevent the window from being visible in the Taskbar.
  • The WindowStyle property has been set to SingleBorderWindow to add a thin border to the window, removing the minimize and maximize buttons from the title bar.
  • The Topmost property has been set to True to keep it always visible on top of other windows. This is optional, but good to have.
  • The ResizeMode property has been set to NoResize to prevent the user from resizing the dialog window.

There's more...

The operating system provides some reusable dialog boxes, which provide a user experience consistent with the version of the operating system in which the application is running. The experience also stays consistent across all applications to provide a unique interface for performing common operations such as opening files, saving files, printing files, color selection, and more.

WPF provides these reusable, common dialog boxes as managed wrapper classes, encapsulating the core implementation. This reduces the extra effort creating and managing the common operations.

Using the open file dialog

To open files in your WPF application, you can use the managed wrapper class OpenFileDialog, which is present under the Microsoft.Win32 namespace. You just have to create the instance and call the ShowDialog() method by optionally setting a few properties for UI customization.

A basic open file dialog looks like the following screenshot, providing you with an option to select one or more files to open:

The following code snippet demonstrates how to initiate the open file dialog by optionally filling the file-extension filter:

private void OnOpenButtonClicked(object sender, RoutedEventArgs e) 
{ 
    var openfileDialog = new OpenFileDialog 
    { 
        Filter = "Text documents (.txt) | *.txt | Log files (.log) | 
        *.log" 
    }; 
 
    var dialogResult = openfileDialog.ShowDialog(); 
    if (dialogResult == true) 
    { 
        var fileName = openfileDialog.FileName; 
    } 
} 

The dialogResult returned by the ShowDialog() method tells us whether the operation was performed successfully. Based on that, you can call the instance of the file dialog to get more details about the selected file.

Using the save file dialog

Along with the OpenFileDialog interface, the Microsoft.Win32 namespace also provides the SaveFileDialog managed wrapper to perform file saving operations from your WPF application. Similar to the open file dialog, you need to create the instance of it by optionally filling its various properties to finally call the ShowDialog() method.

The save file dialog looks like the following screenshot, where you can provide a name to save as a file:

Optionally, you can set the extension filter, default file name, and other properties before launching the dialog window, as shown in the following code snippet:

private void OnSaveButtonClicked(object sender, RoutedEventArgs e) 
{ 
    var saveFileDialog = new SaveFileDialog 
    { 
        Filter = "Text documents (.txt) | *.txt | Log files (.log) |
         *.log" 
    }; 
 
    var dialogResult = saveFileDialog.ShowDialog(); 
    if (dialogResult == true) 
    { 
        var fileName = saveFileDialog.FileName; 
    } 
} 

Based on the dialogResult returned by the ShowDialog() call you can decide whether the save was successful and retrieve more information about the saved file from the file dialog instance.

Using the print dialog

The managed wrapper PrintDialog is also present in the Microsoft.Win32 namespace, and provides you with the interface to call the operating system's printer properties and perform the print operation. The dialog gives you the option to Select Printer, configure the printing preferences, and select the page range and other parameters, as shown in the following screenshot:

To invoke the same, just create the instance of the PrintDialog and call its ShowDialog() method. You can optionally set page range, printable area, and other properties. If the dialogResult returned by the ShowDialog() method is set to true, it confirms that the printing job has been queued up successfully, and based on that you can perform the next set of actions.

Here's the code snippet for your reference:

private void OnPrintButtonClicked(object sender, RoutedEventArgs e) 
{ 
    var printDialog = new PrintDialog(); 
    var dialogResult = printDialog.ShowDialog(); 
 
    if (dialogResult == true) 
    { 
        // perform the print operation 
    } 
} 

Other common dialogs

WPF also provides some other common dialog boxes to perform the selection of various formatting options, such as font, font style, font size, text effects, and color. You can use the FontDialog and ColorDialog, present under the System.Windows.Forms namespace, to add support for the font and color selections, respectively.

Here's the screenshot presenting the font selector and color selector dialogs:

You have been reading a chapter from
Windows Presentation Foundation Development Cookbook
Published in: Feb 2018
Publisher: Packt
ISBN-13: 9781788399807
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime
Visually different images