How To Show Message Dialog In Windows 10

In this article we are going to see how to show a message dialog in your Windows 10 apps on the Desktop and Mobile devices using C# and XAML. The MessageDialog class is available in Windows 10. We now have a Universal Windows Platform (UWP).

Create new Windows 10 UWP app and name it as you wish. Now go to Mainpage.Xaml and paste the following XAML code to create a button for showing message dialog.

  1. <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">  
  2.    <Button x:Name="Showbutton" Click="Showbutton_Click" Content="Show Message Dialog"/>  
  3. </StackPanel>  
Now our design page looks like the following screen:

design page

Now go to code behind page and write the following code on button click event.
  1. private async void Showbutton_Click(object sender, RoutedEventArgs e)  
  2. {  
  3.     MessageDialog showDialog = new MessageDialog("Hi Welcome to Windows 10");  
  4.     showDialog.Commands.Add(new UICommand("Yes")  
  5.     {  
  6.         Id = 0  
  7.     });  
  8.     showDialog.Commands.Add(new UICommand("No")  
  9.     {  
  10.         Id = 1  
  11.     });  
  12.     showDialog.DefaultCommandIndex = 0;  
  13.     showDialog.CancelCommandIndex = 1;  
  14.     var result = await showDialog.ShowAsync();  
  15.     if ((int) result.Id == 0)  
  16.     {  
  17.         //do your task  
  18.     }  
  19.     else  
  20.     {  
  21.         //skip your task  
  22.     }  
  23. }  
Create an instance of the MessageDialog with the Message and Title if required. UICommands are added to the commands collection of the dialog. Default Command index is set to 0 for (Yes) button to invoke user hit the enter key and the Cancel Command index is set to 1 for (No) button to invoke user hit the Escape or No button.

Use ShowAsync() method to show the dialog and check the result containing command id and perform the yes or no task.

Now run your app with Local Machine, Mobile and Simulator to see the output as in the following image.

Local Machine

Local Machine

Mobile

Mobile

Simulator

Simulator

Simulator and Mobile

Simulator and Mobile

Source code.

 


Similar Articles