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.
- <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
- <Button x:Name="Showbutton" Click="Showbutton_Click" Content="Show Message Dialog"/>
- </StackPanel>
Now our design page looks like the following screen:
Now go to code behind page and write the following code on button click event.
- private async void Showbutton_Click(object sender, RoutedEventArgs e)
- {
- MessageDialog showDialog = new MessageDialog("Hi Welcome to Windows 10");
- showDialog.Commands.Add(new UICommand("Yes")
- {
- Id = 0
- });
- showDialog.Commands.Add(new UICommand("No")
- {
- Id = 1
- });
- showDialog.DefaultCommandIndex = 0;
- showDialog.CancelCommandIndex = 1;
- var result = await showDialog.ShowAsync();
- if ((int) result.Id == 0)
- {
-
- }
- else
- {
-
- }
- }
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 Mobile Simulator Simulator and Mobile Source
code.