Sdílet prostřednictvím


Dialog Boxes Overview

Microsoft Silverlight will reach end of support after October 2021. Learn more.

A dialog box is a temporary window an application typically uses to prompt the user for additional information, such as a file to open or specify printer settings prior to printing a document. A dialog box usually contains one or more controls that enable the user to enter text, choose options, or direct the action of the application. Silverlight provides predefined dialog boxes that support messages, opening a file, saving a file, and printing. In addition, there are controls that enable you to create your own dialog boxes. The appearance of a dialog box will vary depending on the operating system that is running the Silverlight application.

This topic contains the following sections.

  • Message Boxes
  • Common Dialog Boxes
  • Custom Dialog Boxes
  • Related Topics

Message Boxes

Silverlight provides a MessageBox that you can use to show a message to the user and solicit a response. To show a message box, you call the static Show(String) method. You can optionally specify a caption and a cancel button for the message box using the Show(String, String, MessageBoxButton) method. The message box is a modal dialog box, which means the user cannot continue until he or she has responded to the message box. You can use the MessageBoxResult object returned from the Show method to determine whether the user clicked OK or Cancel and react accordingly.

The following code example shows how to display a message box with a caption and an OK button.

MessageBox.Show("The application is starting...", "Start Dialog", MessageBoxButton.OK)
MessageBox.Show("The application is starting...", "Start Dialog", MessageBoxButton.OK);

Common Dialog Boxes

Silverlight offers three commonly used modal dialog boxes: a dialog box to open files, save files, and specify print settings. The following sections describe these dialog boxes in more detail.

Security Restrictions for Common Dialog Boxes

For security purposes, if a Silverlight application is a sandboxed application, file and print dialog boxes must be user-initiated. This means you must show them from a user-initiated action, such as the click event handler for a button. If you attempt to show a dialog box from non-user initiated code, a SecurityException will occur. In addition, there is a limit on the time allowed between when the user initiates the dialog and when the dialog is shown. If the time limit between these actions is exceeded, an exception will occur. When you are using the Visual Studio debugger with a dialog box, a SecurityException will be thrown if you set a breakpoint between dialog box creation and showing the dialog box. Because of the user-initiated restrictions, this is the expected behavior. If you set a breakpoint after the call to ShowDialog, no exception will be thrown.

If you attempt to show the dialog box from KeyDown event handlers and other synchronous calls to application code, such as LayoutUpdated or SizeChanged event handlers, an exception will be thrown. However, an exception will not be thrown when the application is hosted in Internet Explorer, running in protected mode.

The Silverlight plug-in has limited support for dialog boxes when the plug-in is in full-screen mode. In most cases, displaying the dialog box in full-screen mode will cause the plug-in to revert to embedded mode. However, to avoid issues on some browsers, you should exit full-screen mode before using these classes. In Silverlight applications that run outside the browser, you can display a prompt to the user to enable dialog boxes in full-screen mode. Also, the user initiation restrictions are relaxed for trusted applications. For more information, see Trusted Applications.

Open File Dialog Box

Silverlight provides an OpenFileDialog control that enables users to select one or more files on the local computer or on a networked computer. The following illustration shows the OpenFileDialog in a Silverlight application running on Windows 7 and hosted in Internet Explorer.

Open File Dialog Box

Open file dialog box.

You can display an open file dialog box by using the ShowDialog method. ShowDialog returns true if the user selected a file and clicked Open, or false if the user clicked Cancel. As mentioned previously, to show the dialog box, the user must take some action, such as clicking a button.

The initial folder displayed the first time the OpenFileDialog is shown for a application is based on the user's settings. Additional displays of the OpenFileDialog use the folder of the last selected file. For security reasons, you cannot specify an initial folder for the OpenFileDialog.

You can filter the file types shown in the OpenFileDialog by using the Filter property. The following is an example of a filter setting.

Text Files (.txt)| *.txt"

You can enable the user to select multiple files to open by using the Multiselect property. Once files are selected, you can retrieve information about the files by using the File or Files property, depending on whether one or multiple files were selected.

The following example shows how to display an OpenFileDialog.

Private ofd As OpenFileDialog
Private Sub OpenButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
    ofd = New OpenFileDialog()
    ofd.Filter = "Text Files (.txt)| *.txt"
    ofd.Multiselect = False
    Dim result As System.Nullable(Of Boolean) = ofd.ShowDialog()

    Dim fileContents As String
    If result = True Then
        Using textStream As System.IO.StreamReader = ofd.File.OpenText()
            fileContents = textStream.ReadToEnd()
        End Using
    End If
End Sub
OpenFileDialog ofd;
private void OpenButton_Click(object sender, RoutedEventArgs e)
{
    ofd = new OpenFileDialog();
    ofd.Filter = "Text Files (.txt)| *.txt";
    ofd.Multiselect = false;
    bool? result = ofd.ShowDialog();

    string fileContents;
    if (result == true)
    {
        using (System.IO.StreamReader textStream = ofd.File.OpenText())
        {
            fileContents = textStream.ReadToEnd();
        }
    }

}
<Button Height="50" Margin="5" Width="100" x:Name="OpenButton" Content="Open" Click="OpenButton_Click"/>

Save File Dialog Box

Silverlight provides a SaveFileDialog control that enables users to save a file on the local computer or on a networked computer.

The following illustration shows a SaveFileDialog in a Silverlight running on Windows 7 and hosted in Internet Explorer.

Save File Dialog Box

Save file dialog box

You show a save file dialog box by using the ShowDialog method. ShowDialog returns true if the

user clicked Save, or false if the user clicked Cancel. As mentioned previously, to show the dialog box, the user must take some action, such as clicking a button.

Similar to the OpenFileDialog, you can filter the file types shown in the SaveFileDialog by using the Filter property. When specified, the filter description appears in the Save as type drop-down list of the dialog box. The following is an example of a filter description.

Text Files (.txt)| *.txt"

For more information about how to specify a filter description, see Filter.

You can specify the default file extension appended to the saved file by using the DefaultExt property.

You can retrieve the name of the saved file by using the SafeFileName property. As the property name indicates, for security reasons, SafeFileName returns only the name of the file without the file path.

The following code example shows how to set the Filter property and display a SaveFileDialog.

    Private sfd As SaveFileDialog
    Private Sub SaveButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        sfd = New SaveFileDialog()
        sfd.Filter = "Video Files (.wmv) | *.wmv"

        Dim result As System.Nullable(Of Boolean) = sfd.ShowDialog()
        If result = True Then
            MessageBox.Show("File saved to" & sfd.SafeFileName)
        End If
    End Sub

SaveFileDialog sfd;
private void SaveButton_Click(object sender, RoutedEventArgs e)
{
    sfd = new SaveFileDialog();
    sfd.Filter = "Video Files (.wmv) | *.wmv";

    bool? result = sfd.ShowDialog();
    if (result == true)
        MessageBox.Show("File saved to" + sfd.SafeFileName);

}
<Button Height="50" Margin ="5" Width="100" x:Name="SaveButton" Content="Save" Click="SaveButton_Click"/>

The Silverlight print dialog box enables users to select print options and perform a print operation. For Silverlight 4 or later, you add a PrintDocument to your application and call the Print method. There is no class for a stand-alone print dialog box. Like the other dialog boxes, a print dialog box can only be displayed when user-initiated.

Within the print dialog box, the user can select the printer settings he or she wants and then click Print to continue the print operation or Cancel to cancel the print operation. The following illustration shows an example of the print dialog box for Windows.

Print Dialog Box

Silverlight Print Dialog

The following example shows how to display a print dialog box.

Private pd As System.Windows.Printing.PrintDocument
Private Sub PrintButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
    ' Create a print document.
    pd = New System.Windows.Printing.PrintDocument()

    ' Show the print dialog.
    pd.Print()
End Sub
System.Windows.Printing.PrintDocument pd;
private void PrintButton_Click(object sender, RoutedEventArgs e)
{
    // Create a print document.
    pd = new System.Windows.Printing.PrintDocument();

    // Show the print dialog.
    pd.Print();
}
<Button Height="50" Margin="5" Width="100" x:Name="PrintButton" Content="Print" Click="PrintButton_Click"/>

For the print operation to occur, you must handle the PrintPage event of the print document and specify the element you want to print.

For more information, see PrintPage and Printing.

Custom Dialog Boxes

There are a couple of different classes that enable you to add custom dialog boxes to your Silverlight applications. This section describes these classes in more detail.

ChildWindow

You can create your own modal dialog boxes by using the ChildWindow control. You display a ChildWindow to the user by calling the Show method. To retrieve the user response, you should handle the Closed event. In the event handler, you should cast the sender parameter to a ChildWindow type and retrieve the value of DialogResult.

Typically you derive from ChildWindow to create a customized dialog box, although you can instantiate a child window directly.

You can easily add a child window to your application by using Visual Studio. In the Add New Item dialog box, select the Silverlight Child Window template, as shown in the following illustration.

Silverlight Templates

The Silverlight Child Window template adds a new class derived from child window to your project including both the XAML and code-behind files. The XAML file contains OK and Cancel buttons and the code-behind file contains click event handlers for each button that set the appropriate dialog box result.

For code examples and more information, see ChildWindow.

You can display a user control in a Popup control similar to a dialog box. To do this, you create a user control that derives from the UserControl class and set the Child property of Popup to an instance of the user control. You display the Popup to the user by setting the IsOpen property to true.

You set the position of a Popup relative to the upper-left corner of the Silverlight plug-in by using the VerticalOffset and HorizontalOffset properties.

For code examples and more information, see Popup.