Windows 10 XAML Tips: MessageDialog and ContentDialog

By Fons Sonnemans, 23-jun-2015

In this blog post I will explain how you can show a message dialog and content dialog in your Windows 10 apps on the Desktop and Mobile (Phone) devices using C# and XAML. The MessageDialog class has been available in WinRT from the start. The ContentDialog class was introduced in Windows Phone 8.1 Universal apps and is now also available in Windows 10 because we now have a true Universal Windows Platform (UWP).

Sample Project

My sample project is a simple Windows 10 Universal app which I created using Visual Studio 2015 RC. It contains a Page with a StackPanel with 4 buttons. The first button will be used to show a message dialog. The other buttons will be used to show content dialogs.

<Page x:Class="ContentDialogDemo.MainPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:local="using:ContentDialogDemo"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      x:Name="pageRoot"
      mc:Ignorable="d">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

        <StackPanel VerticalAlignment="Center"
                    HorizontalAlignment="Center">

            <Button Content="Show MessageDialog"
                    Click="ButtonShowMessageDialog_Click" />
            <Button Content="Show ContentDialog 1"
                    Click="ButtonShowContentDialog1_Click"
                    Margin="0,4" />
            <Button Content="Show ContentDialog 2"
                    Click="ButtonShowContentDialog2_Click" />
            <Button Content="Show ContentDialog 3"
                    Click="ButtonShowContentDialog3_Click"
                    Margin="0,4" />
        </StackPanel>

    </Grid>
</Page>

Show MessageDialog

The ButtonShowMessageDialog_Click method in the code behind of my page shows the message dialog. It creates an instance of the MessageDialog with the Text and the Title. UICommands are added to the Commands collection of the dialog. On Mobile you can only use 2 commands so there is a DeviceFamily check in the code to prevent the app from crashing. The DefaultCommandIndex is set to 0 which means that the first button will be invoked when you hit the Enter key. The CancelCommandIndex is set to 1 which means that the second button will be invoked when you hit the Escape key or the back button on the phone. You show the dialog using the ShowAsync() method which is awaited. The result contains the Id and the Label of the invoked command.

private async void ButtonShowMessageDialog_Click(object sender, RoutedEventArgs e) {

    var dialog = new Windows.UI.Popups.MessageDialog(
                "Aliquam laoreet magna sit amet mauris iaculis ornare. " +
                "Morbi iaculis augue vel elementum volutpat.",
                "Lorem Ipsum");

    dialog.Commands.Add(new Windows.UI.Popups.UICommand("Yes") { Id = 0 });
    dialog.Commands.Add(new Windows.UI.Popups.UICommand("No") { Id = 1 });

    if (Windows.System.Profile.AnalyticsInfo.VersionInfo.DeviceFamily != "Windows.Mobile") {
        // Adding a 3rd command will crash the app when running on Mobile !!!
        dialog.Commands.Add(new Windows.UI.Popups.UICommand("Maybe later") { Id = 2 });
    }

    dialog.DefaultCommandIndex = 0;
    dialog.CancelCommandIndex = 1;

    var result = await dialog.ShowAsync();

    var btn = sender as Button;
    btn.Content = $"Result: {result.Label} ({result.Id})";
}

When you run the app on your computer and click/tap the first button you get a message dialog which is centered in the app window. The default button has a blue background which is the accent color of my computer.

When you run the app on your Windows Phone and tap the first button you get a message dialog which is in the top of the screen. The dialog is dark because the phone has a dark theme setting. The labels of the buttons are always in lowercase.

Show ContentDialog

The ButtonShowContentDialog1_Click method in the code behind of my page shows the first content dialog. It creates an instance of the ConentDialog with the Title and MaxWidth. The MaxWidth property must be set to avoid problems with wide content on small devices. The Content of the dialog is set to StackPanel with the a TextBlock and a CheckBox. The IsChecked property is two-way databound to the IsPrimaryButtonEnabled property of the dialog. The Primary and Secondary buttons are initalized and use a Click event to set the result of the clicked button. If you use the Escape button or the back button on the phone the result will be set to NONE. You can only have one or two buttons.

private async void ButtonShowContentDialog1_Click(object sender, RoutedEventArgs e) {
    var btn = sender as Button;
    var dialog = new ContentDialog() {
        Title = "Lorem Ipsum",
        //RequestedTheme = ElementTheme.Dark,
        //FullSizeDesired = true,
        MaxWidth = this.ActualWidth // Required for Mobile!
    };

    // Setup Content
    var panel = new StackPanel();

    panel.Children.Add(new TextBlock {
        Text = "Aliquam laoreet magna sit amet mauris iaculis ornare. " +
                    "Morbi iaculis augue vel elementum volutpat.",
        TextWrapping = TextWrapping.Wrap,
    });

    var cb = new CheckBox {
        Content = "Agree"
    };

    cb.SetBinding(CheckBox.IsCheckedProperty, new Binding {
        Source = dialog,
        Path = new PropertyPath("IsPrimaryButtonEnabled"),
        Mode = BindingMode.TwoWay,
    });

    panel.Children.Add(cb);
    dialog.Content = panel;

    // Add Buttons
    dialog.PrimaryButtonText = "OK";
    dialog.IsPrimaryButtonEnabled = false;
    dialog.PrimaryButtonClick += delegate {
        btn.Content = "Result: OK";
    };

    dialog.SecondaryButtonText = "Cancel";
    dialog.SecondaryButtonClick += delegate {
        btn.Content = "Result: Cancel";
    };

    // Show Dialog
    var result = await dialog.ShowAsync();
    if (result == ContentDialogResult.None) {
        btn.Content = "Result: NONE";
    }
}

When you run the app on your computer and click/tap the second button you get a content dialog. The position of the dialog can differ depending the size of the app window. The OK button is only enabled when the checkbox is checked.

When you run the app on your Windows Phone and tap the second button you get a content dialog which is always in the top of the screen.

Show ContentDialog using Commands

The ButtonShowContentDialog2_Click method in the code behind of my page uses Commands instead of Events to show the result of the content dialog. The PrimaryButtonCommand is a RelayCommand which has a CanExecute which returns true when the checkbox is checked. I expected that this would disable the primary button but it doesn't. You will still have to databind the checkbox to the IsPrimaryButtonEnabled property. I hope this will change in future versions.

private async void ButtonShowContentDialog2_Click(object sender, RoutedEventArgs e) {
    var btn = sender as Button;
    var dialog = new ContentDialog() {
        Title = "Lorem Ipsum",
        //RequestedTheme = ElementTheme.Dark,
        //FullSizeDesired = true,
        MaxWidth = this.ActualWidth // Required for Mobile!
    };

    var panel = new StackPanel();

    panel.Children.Add(new TextBlock {
        Text = "Aliquam laoreet magna sit amet mauris iaculis ornare. " +
                "Morbi iaculis augue vel elementum volutpat.",
        TextWrapping = TextWrapping.Wrap,
    });

    var cb = new CheckBox {
        Content = "Agree"
    };
    panel.Children.Add(cb);
    dialog.Content = panel;

    // The CanExecute of the Command does not enable/disable the button :-(
    dialog.PrimaryButtonText = "OK";
    var cmd = new Common.RelayCommand(() => {
        btn.Content = "Result: OK";
    }, () => cb.IsChecked ?? false);

    dialog.PrimaryButtonCommand = cmd;

    dialog.SecondaryButtonText = "Cancel";
    dialog.SecondaryButtonCommand = new Common.RelayCommand(() => {
        btn.Content = "Result: Cancel";
    });

    cb.Click += delegate {
        cmd.RaiseCanExecuteChanged();
    };

    var result = await dialog.ShowAsync();
    if (result == ContentDialogResult.None) {
        btn.Content = "Result: NONE";
    }
}

Define ContentDialog in XAML

You can also use XAML instead of creating a content dialog from code. In the next example the ContentDialog is created in the MainPage.xaml and named MyContentDialog. The ButtonShowContentDialog3_Click method in the code behind will use this name to show the dialog and display the result.

<Page x:Class="ContentDialogDemo.MainPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:local="using:ContentDialogDemo"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      x:Name="pageRoot"
      mc:Ignorable="d">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

        <StackPanel VerticalAlignment="Center"
                    HorizontalAlignment="Center">

            <Button Content="Show MessageDialog"
                    Click="ButtonShowMessageDialog_Click" />
            <Button Content="Show ContentDialog 1"
                    Click="ButtonShowContentDialog1_Click"
                    Margin="0,4" />
            <Button Content="Show ContentDialog 2"
                    Click="ButtonShowContentDialog2_Click" />
            <Button Content="Show ContentDialog 3"
                    Click="ButtonShowContentDialog3_Click"
                    Margin="0,4" />
        </StackPanel>

        <ContentDialog x:Name="MyContentDialog"
                        VerticalAlignment="Stretch"
                        Title="Lorem Ipsum"
                        PrimaryButtonText="OK"
                        IsPrimaryButtonEnabled="{Binding IsChecked, ElementName=checkBoxAgree, Mode=OneWay}"
                        SecondaryButtonText="Cancel"
                        MaxWidth="{Binding ActualWidth, ElementName=pageRoot}">
            <StackPanel>
                <TextBlock Text="Aliquam laoreet magna sit amet mauris iaculis ornare. Morbi iaculis augue vel elementum volutpat."
                            TextWrapping="Wrap" />
                <CheckBox x:Name="checkBoxAgree"
                            Content="Agree" />
            </StackPanel>

        </ContentDialog>
    </Grid>
</Page>
private async void ButtonShowContentDialog3_Click(object sender, RoutedEventArgs e) {
    var btn = sender as Button;
    var result = await MyContentDialog.ShowAsync();
    btn.Content = "Result: " + result;
}

Closure and download

I hope you can use this blog for your own Windows 10 apps. You can download the sample project below.

Cheers,

Fons

Tags: XAML, Windows 10

Leave a Comment

Leave a Comment
Name
Comment
7 + 7 =

13 Comments

  • Louise Osullivan
    20 aug 2018 01:12
    Discover The Secret 3-Step Amazon Formula & Start Earning Affiliate Commissions On Demand reflectionit.nl 1.Instantly deploy your new profitable, hands-free Amazon affiliate store. 2.Easily discover the most profitable and viral products to promote. 3.Press one button to build a site that will generate viral traffic and sales on autopilot. GET FREE ACCES ==> http://bit.ly/GET_Amazon_Formula SEND EMAIL WITH [[[ YOUR SITE ]]] ==> unsubscribe_your_site@mail.com <==
  • Nancy Stump
    9 aug 2018 07:28
    The web’s most advanced private proxy service! Test our proxies for your purpose before ordering… TEST NEW FREE ==>> http://bit.ly/Test_Proxies
  • MARIAN CHUI
    18 jul 2018 11:37
    你好!
  • Penny Novak
    15 jul 2018 02:57
    NEW! CONTROVERSIAL Software Exploits $12.3 MILLION LOOPHOLE & Makes Us $519/DAY... You can use the Software to build your own Profiteering Website in under 5 Minutes. Watch the DEMO on this private page == >> http://bit.ly/Five_Minute_Profit_Sites
  • Cheryle Gabriele
    7 jul 2018 05:06
    The 2 Week Diet is an extreme rapid weight loss system that can help you lose up to 16 pounds of pure body fat in just 2 weeks! Get your personalized diet plan for 2 week weight loss, our 14 day diet, and how to lose weight in 2 weeks from our official website. WHAT TAKES MOST DIETS 2-3 MONTHS, THE 2 WEEK DIET ACHIEVES IN ONLY 14 DAYS, INCLUDING… DON'T MISS OUT ==> http://bit.ly/The_2_Week_Diet_Ok
  • Mathew Towle
    1 jul 2018 10:56
    Test apps. Get paid. It’s that easy. Like smartphone apps? Here’s how you can get paid to test them Check out the #1 site for paid app reviews… SEE HERE==> http://bit.ly/Get_Paid_To_Test_Apps
  • Torsten Bussell
    23 jun 2018 10:27
    Hi, just wanted to let you know that the last few chances to get the award-winning free trial of the Rank Tracker software is coming to an end. https://www.track-r.net lets you see exactly where your site is placed in the Google search engine listings against your competitors. Thanks
  • Belle Cocks
    18 jun 2018 11:17
    Discover This Little-Known FREE Software That Generates $80-$100 Per Day... TRAFFIC IS INCLUDED - 100% Newbie Friendly & Takes 3 Minutes To Set Up! - You can start getting results right away - It doesn’t require you to invest any money to get started - You don’t have to spam anyone or use some traffic loophole to do this - It’s PROVEN and it will put $80 - $100 per day in your pocket with just a small amount of work each day (an hour or less most days, which is a very nice hourly wage) - You can scale this over time and make more money if you want… - If you’re tired of all of the hype and methods that promise everything and give you little to nothing in return… THIS IS FOR YOU ==> http://bit.ly/GET_RISERR - BONUS 1 - FREE LIVE WORKSHOP You'll be invited to our closed door webinar only for customers of Riserr where you'll discover how to consistently earn a job replacing income of $4000 per day or MORE... - BONUS 2 - MASTERMIND GROUP You'll get access to our Private Mastermind Group where you can network with us and learn many of our secrets at no extra cost to you... - BONUS 3 - SECRET BONUS This one is a surprise - and I know that you'll absolutely love it, although it's a bit WEIRD! =============================================== - IF YOU DO NOT WANT TO RECEIVE THIS MESSAGE !! - SEND EMAIL WITH YOUR SITE THAT YOU DO NOT WANT TO BE CONTACTED ==> unsubscribe_your_site@mail.com <== ===============================================
  • Renaldo Derr
    12 jun 2018 06:01
    LEARN How to earn $500 per month from ClixSense !! “METHOD TESTED BY ME” You can see there are number of ways in ClixSense to make money. I will explain you each of the method so that you can make a big income from ClixSense. Your income will be slow for the first months and after that you will be able to make better income. Watch this video ==> https://youtu.be/iGeAsP2bsNY =============================================== - IF YOU DO NOT WANT TO RECEIVE THIS MESSAGE !! - SEND EMAIL WITH PAGE LINKS THAT YOU DO NOT WANT TO BE CONTACTED ==> unsubscribe_for@myself.com <== ===============================================
  • Sofia Persinger
    6 jun 2018 12:18
    LEARN How to earn $500 per month from ClixSense !! “METHOD TESTED BY ME” You can see there are number of ways in ClixSense to make money. I will explain you each of the method so that you can make a big income from ClixSense. Your income will be slow for the first months and after that you will be able to make better income. Watch this video: http://bit.ly/Learn_ClixSense
  • Jermaine Miele
    27 mei 2018 10:53
    Getting Paid To Test Apps With AppCoiner Is As Simple As 1,2,3! (We accept members from every country in the world!) Watch this: http://bit.ly/Test_App
  • Tony Henrique
    21 mei 2018 04:52
    Very nice
  • vikrant Singh
    16 aug 2017 04:58
    Can we use this messagebox in Usercontrol because i am getting error.

All postings/content on this blog are provided "AS IS" with no warranties, and confer no rights. All entries in this blog are my opinion and don't necessarily reflect the opinion of my employer or sponsors. The content on this site is licensed under a Creative Commons Attribution By license.