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
3 + 5 =

25 Comments

  • 카지노사이트추천
    12 nov 2018 08:22
    If you see a listing of four blog posts, three with “6 comments” listed, and one with “145 comments” listed, which post are you going to dive into?Probably the 145-comment post. Clearly there is something going on there and lots of people are actively talking.
  • 슬롯머신
    12 nov 2018 08:22
    Taking part in blog comment sections makes it easier for readers who find the post to follow along and make sense of how the discussion goes. Latecomers can see what has already been said.
  • 하이게이밍
    12 nov 2018 08:21
    Admittedly, some of the social features of some comment systems that adjust the order of the comments according to votes by readers can be confusing, as they aren’t a threaded in-order conversation. While that technique helps commenters police out bad comments (in theory) it does add to confusion, too. But, at least all of the discussion is in one place.
  • 카지노사이트주소
    12 nov 2018 08:21
    Some might be on Twitter (where following a discussion is like chasing the tail of a kite on a windy day), others on Google+. Different people saying interesting things, but because those multiple conversations are on different platforms? Never the two shall meet. And, conversation on social media fades away as the news feeds change. It’s always been a frustration of mine that this happens.
  • 퍼스트카지노
    12 nov 2018 08:21
    I learned early on as a small town newspaper reporter that mentioning the names of people in the community in stories, and featuring their kids in school activities, was how you sold papers. It’s the same reason people buy that expensive “Who’s Who” book: they’re listed in it.
  • Arnette Adamson
    8 nov 2018 04:05
    Hi I have a small question about a product that you sell. I would like to know, what is the difference with the product in this webshop http://bit.ly/Clothingitem235 and the clothes you sell in your shop. thank you for your time. greetings
  • Dan Martin
    26 okt 2018 06:01
    Hi I'd like to show you our new software that all website owners or users should try out. It shows you exactly where your website is placed in Google and we give you never-seen-before tips on how to increase your rankings for FREE. Prices start at just $19.99pm. If you search in Google while logged in, you get skewed results, so our bespoke software uses a combined pool of random IPs to give you an exact result. It is VITAL data for anyone that handles or owns a website. Increasing your rankings in Google is imperative to your website's success. Even if you use social media or other forms of marketing, having a top #3 placement for your target keywords gives you passive traffic to your site. https://www.track-r.net -> there's a 7 day free trial. If you like it, then the low payment comes out automatically. If you want to cancel, just hit Subscriptions>Cancel. We launched in April and are dominating our own industry. With over 500 customers, our 1,000 target before Xmas is looking good. Let us help you and in turn we can achieve our target. Our Black Friday deal is in play now, we doubled the amount of keywords for the same price....this is staying put....for now....join us and lock in your package today. Track-R.net
  • Jung Madera
    26 okt 2018 12:02
    Hi My compliments for you beautiful website what you have made. I had visited your website last month to order something, but unfortunately I did not have enough money to buy it, but today because I had enough money, I wanted to order it from you, but I can not find the product anymore in you shop, it looks like this on this blog http://bit.ly/BlogFasionitem635 i can order it from someone else, but would like to buy it from you, I hope you will sell the product again soon, mail me if you are going to sell it again, I'll wait. Greets
  • Susan Janousek
    25 okt 2018 01:03
    Dear Sir/Madam, Wonderful to fulfill you. I am Joseph from Bluetooth Gadget Ltd, a Hong Kong based modern technology firm focused on Bluetooth and also cordless items consisting of: Bluetooth headsets, audio speakers, adapters, charging tools as well as variety of auto accessories. Today product: Bluetooth Mobile Gamepad/ Game Controller for Android/ IPHONE Mobile Phone/ PC/ Smart TELEVISION (PUBG!) Offering factor 1: 6 hour continous Selling point 2: Top-notch switches, high delicate, precision and also incredibly long lasting (1M+ pushing test) The shortcut to be the solid in the games is not to train, yet to be outfitted! Please check our improved version of game controller, developed for the most popular mobile games today. Our designers invested over half year to choose the top product from hundreds for this controller, just to quest for the very best experience and also satisfaction of playing video games. Due to the fact that we are Video game Lovers! High delicate! Durable battery! Super Sturdy! Link for more information: https://www.bluetooth-device.com/index.php?route=product/product&product_id=134 We only create finest products, both in feature as well as outlook design. Have a nice day! Best regards, Joseph Sales Manager Bluetooth Device 6F Leader Industrial Centre, 57 Au Pui Wan Street, Fo Tan, Hong Kong Whatsapp/wechat: 852-64628287 Email: sales@bluetooth-device.com
  • Marco Woods
    17 okt 2018 04:15
    Precious Sir/Madam, Nice to meet you. I am Joseph from Bluetooth Device Ltd, a Hong Kong based modern technology firm focused on Bluetooth and cordless items consisting of: Bluetooth headsets, audio speakers, adapters, billing devices and also selection of vehicle accessories. Today item: Hifi Top Quality Bass Stereo Mini Portable Wireless Bluetooth Speakers (Metal Colours). Selling factor 1: High Sound Quality with Bluetooth V4.1. Selling factor 2: 5W in tiny cutie style, Easy to lug, ideal for exterior. Have you located that the majority of the wireless speaker are either inadequate sound top quality or also heavy to bring outside? Please check our improved version of Bluetooth V4.1 mini audio speaker! Our engineers invested over half year to choose the leading material from hundreds for this small audio speaker, simply to search for the best audio high quality amongst the comparable audio speakers. Due to the fact that we were Music Lovers who started up with Do It Yourself Tube Preamp since 2008! Hi-Fi High quality! Durable battery! Grand Metallic Colors! Connect to learn more: https://www.bluetooth-device.com/index.php?route=product/product&product_id=125 We only create best items, both in feature and also outlook design. Hi-Fi High quality! Lengthy long lasting battery! Grand Metallic Color Styles! Have a nice day! Best regards, Matthew Sales Manager Bluetooth Device 6F Leader Industrial Centre, 57 Au Pui Wan Street, Fo Tan, Hong Kong Whatsapp/wechat: 852-64628287 Email: sales@bluetooth-device.com
  • Robert Bourassa
    7 okt 2018 04:31
    I Will Promote Your Business Via 60,000,000 Real People From Worldwide To Any Niche For Your Business By Contacting Site Webmasters In Your Niche... So you can contact the right audience with offers, driving traffic to your website: - Show your business/services/video’s to a targeted audience. - Requesting link exchanges from other sites in a similar niche. - Contacting webmasters about potentially advertising on their sites - Research and information requests from any targeted web sources - Sending out guest posting and submission requests - Getting in contact with potential affiliates to show your services or products - Contacting a targeted audience to submit press releases - Locating the right people to review your product and services GET NOW ==>> http://bit.ly/Promote_Your_Business =================================================== Want to change how you receive these emails ? UNSUBSCRIBE == > http://bit.ly/Unsubscribable_Site Kind Regards, Axyy Splaiul Independentei, Sectorul 3, 030099
  • Joanna Bickford
    27 sep 2018 07:25
    Dear Sir/Madam, Good to fulfill you. I am Matthew from Bluetooth Device Ltd, a Hong Kong based modern technology firm specialized in Bluetooth and also cordless products consisting of: Bluetooth headsets, audio speakers, adapters, charging devices and also selection of accessories. Today item: 2 in 1 Digital Drafting Board/ Note Pad/ Composing Tablet + Phone Situation for Iphones X 8 7 6 Required an electronic pen to attract or drop notes something for your iphone? Right here comes an Iphone situation that you might do so. Great for revealing/ taping your suggestion, informing your kids and also altering the skin of your case anytime! Even more details below: https://www.bluetooth-device.com/index.php?route=product/product&product_id=149 We just produce ideal products, both in feature and also expectation layout Farewell! Ideal relates to, Matthew Sales Manager Bluetooth Tool 6F Leader Industrial Centre, 57 Au Pui Wan Road, Fo Tan, Hong Kong Whatsapp/wechat: 852-64628287 Email: sales@bluetooth-device.com Why pick us? Most current organisation design-- Suppliers union to save your time and also price We created a Mobile Add-on Manufacturers Union with our extremely- closed manufacturing facilities and we owned the company shares each various other to make sure that merchandisers can place orders for different mobile accessories products in an easier way without the unnecessary expense by trading firms.
  • 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.