MessageDialog MessageDialog MessageDialog MessageDialog Class

Represents a dialog for showing messages to the user.

Syntax

Declaration

public sealed class MessageDialogpublic sealed class MessageDialogPublic NotInheritable Class MessageDialogpublic sealed class MessageDialog

Remarks

Important

You should use MessageDialog only when you are upgrading a Universal Windows 8 app that uses MessageDialog, and need to minimize changes. For new apps in Windows 10, we recommend using the ContentDialog control instead.

Note

This class is not agile, which means that you need to consider its threading model and marshaling behavior. For more info, see Threading and Marshaling (C++/CX) and Using Windows Runtime objects in a multithreaded environment (.NET).

The dialog has a command bar that can support up to 3 commands in desktop apps, or 2 commands in mobile apps. If you don't specify any commands, then a default command is added to close the dialog.

The dialog dims the screen behind it and blocks touch events from passing to the app's canvas until the user responds.

Message dialogs should be used sparingly, and only for critical messages or simple questions that must block the user's flow.

Here's an example of a dialog created by the code in the Examples section.

Message dialog with two commands

Examples

The following example shows how to add commands to a message dialog and display it. For the full code example, see Message dialog sample.

#include "pch.h"
#include "CancelCommand.xaml.h"

using namespace MessageDialogSample;

using namespace Windows::UI::Popups;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Navigation;

void MessageDialogSample::CancelCommand::CancelCommandButton_Click(Platform::Object^ sender,
    Windows::UI::Xaml::RoutedEventArgs^ e)
{
    // Create the message dialog and set its content
    MessageDialog^ msg = ref new MessageDialog("No internet connection has been found.");

    // Add commands and set their callbacks.
    // Both commands use the same callback function instead of inline event handlers.
    UICommand^ continueCommand = ref new UICommand(
        "Try again", 
        ref new UICommandInvokedHandler(this, &CancelCommand::CommandInvokedHandler));
    UICommand^ upgradeCommand = ref new UICommand(
        "Close", 
        ref new UICommandInvokedHandler(this, &CancelCommand::CommandInvokedHandler));

    // Add the commands to the dialog
    msg->Commands->Append(continueCommand);
    msg->Commands->Append(upgradeCommand);

    // Set the command that will be invoked by default
    msg->DefaultCommandIndex = 0;

    // Set the command to be invoked when escape is pressed
    msg->CancelCommandIndex = 1;

    // Show the message dialog
    msg->ShowAsync();
}

void CancelCommand::CommandInvokedHandler(Windows::UI::Popups::IUICommand^ command)
{
    // Display message
    rootPage->NotifyUser("The '" + command->Label + "' command has been selected.", 
        NotifyType::StatusMessage);
}

using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using SDKTemplate;
using System;

private async void CancelCommandButton_Click(object sender, RoutedEventArgs e)
{
    // Create the message dialog and set its content
    var messageDialog = new MessageDialog("No internet connection has been found.");

    // Add commands and set their callbacks; both buttons use the same callback function instead of inline event handlers
    messageDialog.Commands.Add(new UICommand(
        "Try again", 
        new UICommandInvokedHandler(this.CommandInvokedHandler)));
    messageDialog.Commands.Add(new UICommand(
        "Close", 
        new UICommandInvokedHandler(this.CommandInvokedHandler)));

    // Set the command that will be invoked by default
    messageDialog.DefaultCommandIndex = 0;

    // Set the command to be invoked when escape is pressed
    messageDialog.CancelCommandIndex = 1;

    // Show the message dialog
    await messageDialog.ShowAsync();
}

private void CommandInvokedHandler(IUICommand command)
{
    // Display message showing the label of the command that was invoked
    rootPage.NotifyUser("The '" + command.Label + "' command has been selected.", 
        NotifyType.StatusMessage);
}
Imports Windows.UI.Popups
Imports Windows.UI.Xaml
Imports Windows.UI.Xaml.Controls
Imports Windows.UI.Xaml.Navigation
Imports SDKTemplate

Partial Public NotInheritable Class CloseCommand
    Inherits SDKTemplate.Common.LayoutAwarePage

    ' A pointer back to the main page.  This is needed if you want to call methods in MainPage such
    ' as NotifyUser()
    Private rootPage As MainPage = MainPage.Current

    Public Sub New()
        Me.InitializeComponent()
    End Sub

    Private Async Sub CloseCommandLaunch_Click(sender As Object, e As RoutedEventArgs)
        ' Create the message dialog and set its content and title
        Dim messageDialog = New MessageDialog("No internet connection has been found.")

        ' Add buttons and set their callbacks
        messageDialog.Commands.Add(New UICommand("Try again", Sub(command)
            rootPage.NotifyUser("The '" & command.Label & "' button has been selected.", _ 
                NotifyType.StatusMessage)
                                                              End Sub))

        messageDialog.Commands.Add(New UICommand("Close", Sub(command) 
            rootPage.NotifyUser("The '" & command.Label & "' button has been selected.", _
                NotifyType.StatusMessage)
                                                          End Sub))

        ' Set the command that will be invoked by default
        messageDialog.DefaultCommandIndex = 0

        ' Set the command to be invoked when escape is pressed
        messageDialog.CancelCommandIndex = 1

        ' Show the message dialog
        Await messageDialog.ShowAsync
    End Sub
End Class
(function () {
    "use strict";
    var page = WinJS.UI.Pages.define("/html/cancelcommand.html", {
        ready: function (element, options) {
            element.querySelector("#cancelCommand").addEventListener(
                "click", 
                cancelCommand_Click, false);
        }
    });

    // Click handler for the 'cancelCommand' button.
    // Demonstrates setting the command to be invoked when the 'escape' key is pressed.
    // Also demonstrates retrieval of the label of the chosen command and setting a 
    // callback to a function.
    // A message will be displayed indicating which command was invoked.
    // In this scenario, 'Try again' is selected as the default choice, and the 
    // 'escape' key will invoke the command named 'Close'
    function cancelCommand_Click() {
        // Create the message dialog and set its content
        var msg = new Windows.UI.Popups.MessageDialog(
            "No internet connection has been found.");

        // Add commands and set their command handlers
        msg.commands.append(new Windows.UI.Popups.UICommand(
            "Try again", 
            commandInvokedHandler));
        msg.commands.append(
            new Windows.UI.Popups.UICommand("Close", commandInvokedHandler));

        // Set the command that will be invoked by default
        msg.defaultCommandIndex = 0;

        // Set the command to be invoked when escape is pressed
        msg.cancelCommandIndex = 1;

        // Show the message dialog
        msg.showAsync();
    }

    function commandInvokedHandler(command) {
        // Display message
        WinJS.log && WinJS.log("The '" + command.label + "' command has been selected.", 
        "sample", "status");
    }
})();

Constructors summary

Initializes a new instance of the MessageDialog class to display an untitled message dialog that can be used to ask your user simple questions.

The dialog dims the screen behind it and blocks touch events from passing to the app's canvas until the user responds.

Message dialogs should be used sparingly, and only for critical messages or simple questions that must block the user's flow.

Initializes a new instance of the MessageDialog class to display a titled message dialog that can be used to ask your user simple questions.

Properties summary

Gets or sets the index of the command you want to use as the cancel command. This is the command that fires when users press the ESC key.

Add the commands before you set the index.

Gets an array of commands that appear in the command bar of the message dialog. These commands makes the dialog actionable.

Get this array and add UICommand objects that represent your commands to it. If the dialog is currently showing, the commands aren't added to the command bar.

Gets or sets the message to be displayed to the user.

Gets or sets the index of the command you want to use as the default. This is the command that fires by default when users press the ENTER key.

Add the commands before you set the index.

Gets or sets the options for a MessageDialog.

Gets or sets the title to display on the dialog, if any.

Methods summary

Begins an asynchronous operation showing a dialog.

Constructors

  • MessageDialog(String)
    MessageDialog(String)
    MessageDialog(String)
    MessageDialog(String)

    Initializes a new instance of the MessageDialog class to display an untitled message dialog that can be used to ask your user simple questions.

    The dialog dims the screen behind it and blocks touch events from passing to the app's canvas until the user responds.

    Message dialogs should be used sparingly, and only for critical messages or simple questions that must block the user's flow.

    public MessageDialog(String content)public New(String content)Public Sub New(content As String)public MessageDialog(String content)

    Parameters

    • content
      System.String
      System.String
      System.String
      System.String

      The message displayed to the user.

    Remarks

    When localizing the content of a message dialog with string resources (WinJS.Resources), the lang property returned by the getString method is applied by the MessageDialog constructor automatically. You cannot specify this property in the constructor.

  • MessageDialog(String, String)
    MessageDialog(String, String)
    MessageDialog(String, String)
    MessageDialog(String, String)

    Initializes a new instance of the MessageDialog class to display a titled message dialog that can be used to ask your user simple questions.

    public MessageDialog(String content, String title)public New(String content, String title)Public Sub New(content As String, title As String)public MessageDialog(String content, String title)

    Parameters

    • content
      System.String
      System.String
      System.String
      System.String

      The message displayed to the user.

    • title
      System.String
      System.String
      System.String
      System.String

      The title you want displayed on the dialog.

    Remarks

    When localizing the content of a message dialog with string resources (WinJS.Resources), the lang property returned by the getString method is applied by the MessageDialog constructor automatically. You cannot specify this property in the constructor.

Properties

  • CancelCommandIndex
    CancelCommandIndex
    CancelCommandIndex
    CancelCommandIndex

    Gets or sets the index of the command you want to use as the cancel command. This is the command that fires when users press the ESC key.

    Add the commands before you set the index.

    public uint CancelCommandIndex { get; set; }public uint CancelCommandIndex { get; set; }Public ReadWrite Property CancelCommandIndex As uintpublic uint CancelCommandIndex { get; set; }

    Property Value

    • uint
      uint
      uint
      uint

      The index of the cancel command.

    Remarks

    Use message dialogs to send critical or blocking messages and questions from the app.

    ValueWhen to use
    ≥ 0The dialog offers a safe default choice that is the equivalent of cancellation, like "Cancel" or "Close." Set CancelCommandIndex to the index of the command handler for that cancel/close command, so that when the user dismisses the dialog through a noncommital action, like pressing ESC, the API returns the command handler you want. > [!NOTE] > Generally, you should avoid creating dialogs that can be dismissed this way and that re-launch asking the same question or sending the same message again and again. They make the app noisy and tend to annoy users.
    -1The user is required to make an explicit decision like tapping a specific button on the dialog. This ensures that the user can't dismiss the dialog through a noncommital action like pressing ESC.
    -2Not recommended.The dialog is not dismissed when the user presses ESC or during an incoming contract activation; however, if the app re-uses the main app window when responding to incoming activations, the dialog's command handlers will no longer be valid. Because the API doesn't handle this behavior, we recommend not using this value.

    Error handling on dismissal by a contract activationIf the app receives an incoming contract activation (like from Search, Share, Settings, Devices or the file picker contracts) while the dialog is showing, the dialog is programmatically dismissed, regardless of the property value that has been set for the CancelCommandIndex.

    To help you handle this case, the API returns a dummy command handler. You, then, can decide how to handle and react to the error.

  • Commands
    Commands
    Commands
    Commands

    Gets an array of commands that appear in the command bar of the message dialog. These commands makes the dialog actionable.

    Get this array and add UICommand objects that represent your commands to it. If the dialog is currently showing, the commands aren't added to the command bar.

    public IVector<IUICommand> Commands { get; }public IVector<IUICommand> Commands { get; }Public ReadOnly Property Commands As IVector<IUICommand>public IVector<IUICommand> Commands { get; }

    Property Value

    • The commands.

    Remarks

    By default, the array of commands for a dialog is empty. If no commands are appended to this array, then a default "Close" command is shown on the dialog.

    To delay interaction with commands for a short period when the dialog is first shown, set the AcceptUserInputAfterDelay option with MessageDialogOptions.

  • Content
    Content
    Content
    Content

    Gets or sets the message to be displayed to the user.

    public string Content { get; set; }public string Content { get; set; }Public ReadWrite Property Content As stringpublic string Content { get; set; }

    Property Value

    • string
      string
      string
      string

      The message to be displayed to the user.

    Remarks

    Use the content to convey the objective of the dialog. Present the message, error or blocking question as simply as possible without extraneous information.

    When a Title is used, use the content to present additional information helpful to understanding or using the dialog. You can use this area to provide more detail or define terminology. Don't repeat the title with slightly different wording.

  • DefaultCommandIndex
    DefaultCommandIndex
    DefaultCommandIndex
    DefaultCommandIndex

    Gets or sets the index of the command you want to use as the default. This is the command that fires by default when users press the ENTER key.

    Add the commands before you set the index.

    public uint DefaultCommandIndex { get; set; }public uint DefaultCommandIndex { get; set; }Public ReadWrite Property DefaultCommandIndex As uintpublic uint DefaultCommandIndex { get; set; }

    Property Value

    • uint
      uint
      uint
      uint

      The index of the default command.

  • Options
    Options
    Options
    Options

    Gets or sets the options for a MessageDialog.

    public MessageDialogOptions Options { get; set; }public MessageDialogOptions Options { get; set; }Public ReadWrite Property Options As MessageDialogOptionspublic MessageDialogOptions Options { get; set; }

    Property Value

    Remarks

    You can't change options after the dialog displays.

    To delay interaction with commands for a short period when the dialog is first shown, set the AcceptUserInputAfterDelay option with MessageDialogOptions.

  • Title
    Title
    Title
    Title

    Gets or sets the title to display on the dialog, if any.

    public string Title { get; set; }public string Title { get; set; }Public ReadWrite Property Title As stringpublic string Title { get; set; }

    Property Value

    • string
      string
      string
      string

      The title to display on the dialog; or, an empty string if no title is set.

    Remarks

    Use the title as a concise main instruction to convey the objective of the dialog.

    Long titles do not wrap and will be truncated.

    If you use the dialog to deliver a simple message, error, or question, omit the title. Rely on the Content to deliver that core information.

    On the desktop device family the title is displayed both in the title bar of the popup dialog window, and in the body of the dialog. On the mobile device family, the title is shown only in the body of the dialog.

Methods

  • ShowAsync()
    ShowAsync()
    ShowAsync()
    ShowAsync()

    Begins an asynchronous operation showing a dialog.

    public IAsyncOperation<IUICommand> ShowAsync()public IAsyncOperation<IUICommand> ShowAsync()Public Function ShowAsync() As IAsyncOperation( Of IUICommand )public IAsyncOperation<IUICommand> ShowAsync()

    Returns

    Remarks

    In some cases, the system may close the dialog, like when people invoke an app contract when the dialog is showing. IAsyncOperation<TResult> returns either the command selected which destroyed the dialog, or an empty command.

    To launch subsequent dialogs or other modal UI such as file pickers after a dialog has been closed, use the then or done functions of the Promise object. You cannot launch modal UI from within a UICommand callback.

    Calling showAsync while the splash screen is being displaye

    d

    • In : Your app can call ShowAsync() from within the activated handler (the onactivated event or the Activated ), and paint operations then occur behind the app's splash screen.
    • Beginning in : Windows suppresses painting while the app is behind the splash screen to reduce wasteful operations. Your app should not call ShowAsync() from within the activated handler, but should instead wait for the visibility changed notification (the visibilitychange event or the VisibilityChanged ).

Device family

Windows 10 (introduced v10.0.10240.0)

API contract

Windows.Foundation.UniversalApiContract (introduced v1)

Attributes

Windows.Foundation.Metadata.ActivatableAttribute
Windows.Foundation.Metadata.ContractVersionAttribute
Windows.Foundation.Metadata.MarshalingBehaviorAttribute
Windows.Foundation.Metadata.MuseAttribute

Details

Assembly

Windows.UI.Popups.dll